Skip to content

Instantly share code, notes, and snippets.

@rjperrella
Created May 31, 2020 02:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjperrella/3b131dcac56553d51f5800d7d18ffebf to your computer and use it in GitHub Desktop.
Save rjperrella/3b131dcac56553d51f5800d7d18ffebf to your computer and use it in GitHub Desktop.
binary search in perl, using the goto form of tail-recursion elimination
#!/usr/bin/perl
use Test::Simple tests=>4;
sub bsearch {
my ($aref, $item, $lo, $hi) = @_;
return -1 if $lo > $hi;
my $mid = ($hi + $lo) >> 1;
return $mid if ($aref->[$mid] == $item);
if ($item > $aref->[$mid]) {
@_ = ($aref, $item, $mid+1, $hi);
goto &bsearch;
}else{
@_ = ($aref, $item, $lo, $mid - 1);
goto &bsearch;
}
}
my @a = (-1,0,1,3,5,6,7,9);
my $len = @a - 1;
ok(-1 == bsearch(\@a, 4, 0, $len));
ok(3 == bsearch(\@a, 3, 0, $len));
ok(2 == bsearch(\@a, 1, 0, $len));
ok(7 == bsearch(\@a, 9, 0, $len));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment