Algorithms/Find maximum/perl method2

From Wikibooks, open books for an open world
Jump to: navigation, search

perl source code

sub findmax_apple(){
        return 0 if $#_ == -1;
        return $_[0] if $#_ == 0;
 
        if ( $#_ == 1 ) {
                return $_[0] if $_[0] > $_[1];
                return $_[1];
        }
 
        my @aryA;
        my @aryB;
 
        foreach my $i ( 1 .. ($#_+1)/2 ){
                push ( @aryA, $_[ $i - 1 ] );
        }
 
        foreach my $i ( $#aryA + 1 .. $#_ ){
                push ( @aryB, $_[$i] );
        }
 
        my $intM = &findmax_apple(@aryA);
        my $intN = &findmax_apple(@aryB);
        return $intM if $intM > $intN;
        return $intN;
}

An example of using the subroutine:

print &findmax_apple(qw/ 1 100 182 32 476 /);

The output should be: 476.