in reply to Binary search algorithm
Others have dealt with your direct questions, id just like to point out that binary searching an array is almost never done recursively. Theres absolutely no need. Nor do I see why array slices would be useful here at all.
use strict; use warnings; sub bin_search { my $array = shift; my $find = shift; return unless @$array; 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; } my @list=map { $_*2 } (1..5); for (0..11) { my $pos=bin_search(\@list,$_); print "Search:$_ Position:",defined $pos ? $pos : "undef","\n"; }
HTH
|
|---|