in reply to Binary searching with Perl.

There is a mistake in your algorithm. Your $mid position is being set incorrectly.

$mid = ( $low + $high ) / 2;

should become

$mid = int(( $low + $high ) / 2);

See also Binary search algorithm for more examples and discussion about this matter

update Fixed my own mistake. The error was there, but in the wrong place. The original algorithm does not catch the highest index item.

update (2) Jon Bentley in Programming Pearls advised that binary search can be tricky, and even experienced programmers can fail to get it properly. He is right. I have corrected this script three times, every time in the wrong way. Finally, when I monitored the three variables, I got the (hopefully) right path. :)

_ _ _ _ (_|| | |(_|>< _|

Replies are listed 'Best First'.
Re: Re: Binary searching with Perl.
by arthas (Hermit) on May 24, 2003 at 11:40 UTC
    > even experienced programmers can fail to get it properly.

    There's always the "CPAN module" option. ;-)

    Search::Binary

    Michele.