Nelson Castillo wrote:
On Sun, Apr 13, 2008 at 3:10 PM, John W. Krahn <[EMAIL PROTECTED]> wrote:
(cut)

   my $c = &$cmpf($arr->[$mid], $value);

 That is usually written as:


      my $c = $cmpf->($arr->[$mid], $value);

Thanks Chas. and John for your feedback. I think I'm happy with this version:

#!/usr/bin/perl -w

use strict;

# By sefault it works on strings
sub binary_search {
  my $arr = shift;
  my $value = shift;
  my $cmpf = shift || sub {$_[0] cmp $_[1]};

  my $left = 0;
  my $right = $#$arr;

  while ($left <= $right) {
    my $mid = ($right + $left) >> 1;
    my $c = $cmpf->($arr->[$mid], $value);
    return 1
      if ($c == 0);
    if ($c > 0) {
      $right = $mid - 1
    } else {
      $left  = $mid + 1
    }
  }
 return 0
}

my @arr = qw(1 2 3 11); # the array must be sorted

print "searching in @arr\n";
print "Let's use a string comparison function first\n";

for (0, 2, 3, 11, 12)
{
        print "is $_ there? => " . binary_search([EMAIL PROTECTED], $_) . "\n"
}

That won't work correctly unless the numbers are sorted correctly:

$ perl -le' print for sort { $a cmp $b } 0, 2, 3, 11, 12'
0
11
12
2
3



John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order.                            -- Larry Wall

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to