I would like to implement a binary search algorithm in Perl. My "array" is sorted in descending order (not the actual array, but a function that takes an index and returns values). the problem is that there can be stretches of the same values. If my search value is in such a stretch, I want to return the first index that contains it.
Here is what I wrote:
# get_val should be a *decreasing* function for idexes $i in min..max,
and this is a simple example of its use:
sub get_val_sub { my ( $pos, $a ) = @_; my $val = $a->[$pos]; return $val; } my @arr = (80, 40, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0); say "RET:", binary_search( 0, $#arr, 0, \&get_val_sub, \@arr );
The problem is that I'm not sure that my last file (marked ## SEE MY QUESTION BELOW ## ) is "pretty." Is there a better way to do this?