# Takes an array ref and a target item # Returns the index of the item in the array or # -1 if its not there. sub binsearch { my $arref = shift; my $target = shift; my $len = scalar @$arref; my $midpoint = floor( $len / 2); # Get the center, rounding down when we have 1 element left we don't get undef my $cmp = $target cmp $arref->[$midpoint]; # make the comparison once return $midpoint unless $cmp; # We've found it! return -1 if $len == 1; # Must not be there return binsearch ([$arref->[0..$midpoint],$target) if $cmp == -1; # Its in the lower half, check to the midpoint because its rounded down return binsearch ([$arref->[$midpoint+1..$len-1],$target) if $cmp == 1; # Its in the upper half, check to the midpoint +1 for reason stated above croak "Something really weird happened. Might want to run make test on perl itsself."; }