Recently I need to implement a binary searching with perl, so I got this code:
use strict;
use warnings;
my $want = shift;
die "$0 number" unless defined $want;
my @list= (3,5,7,11,13,17,19);
my $pos=bin_search(\@list,$want);
print "Position: ", defined $pos ? $pos : "undef","\n";
# binary search
sub bin_search {
my $array = shift;
my $find = shift;
my ($l,$r)=(0,$#$array);
while ($l<=$r) {
my $m=int(($l+$r)/2);
if ($find<$array->[$m]) {
$r=$m-1;
} elsif ($find>$array->[$m]) {
$l=$m+1;
} else {
return $m;
}
}
return undef;
}
It’s smart. Run it this way:
$ perl binarysearch.pl 11
Position: 3
$ perl binarysearch.pl 13
Position: 4
$ perl binarysearch.pl 15
Position: undef
It’s much faster than loop through the entire array to match the element.