Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
sub binarySearch ### sample call: $returnValue = binarySearch($begin +, $query, \@ArrayPtr); { my ($begin, $query, $ArrayPtr); ### begin = 1 or 0 ($begin, $query, $ArrayPtr) = @_; my(@array) = @$ArrayPtr; ### Handling cases when query is out of bounds return 0 if ($query < $array[0] && $begin == 1); return $#array if ($query > $array[$#array] && $begin == 0); my ($left) = 0; my ($right) = $#array; my ($center); my ($prevCenter) = -1; while(1) { $center = int (($left + $right)/2 ); if ($query == $array[$center]) { if ($begin == 1) { while($center > 0 && $array[$center] == $array[$center-1]) { $center = $center - 1; } } else { while($center < $#array && $array[$center] == $array[$center+1 +]) { $center = $center + 1; } } undef @array; return $center; } if ($center == $prevCenter) { undef @array; return $right if ($begin == 1); return $right-1 if ($begin == 0); } $right = $center if ($query < $array[$center]); $left = $center if ($query > $array[$center]); $prevCenter = $center; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: My Binary Search Perl code takes forever
by blokhead (Monsignor) on Dec 15, 2007 at 15:49 UTC | |
by Anonymous Monk on Dec 15, 2007 at 16:07 UTC | |
by Anonymous Monk on Dec 15, 2007 at 16:29 UTC | |
|
Re: My Binary Search Perl code takes forever
by ikegami (Patriarch) on Dec 15, 2007 at 17:09 UTC | |
by Anonymous Monk on Dec 15, 2007 at 19:00 UTC | |
by ikegami (Patriarch) on Dec 15, 2007 at 22:23 UTC | |
|
Re: My Binary Search Perl code takes forever
by Limbic~Region (Chancellor) on Dec 15, 2007 at 19:29 UTC | |
by Anonymous Monk on Jun 11, 2009 at 10:46 UTC |