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"
}

print "\nNow let's use a numerical comparison function\n";

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

Thanks,
Nelson.-

-- 
http://arhuaco.org

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


Reply via email to