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. :)

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

In reply to Re: Binary searching with Perl. by gmax
in thread Binary searching with Perl. by DigitalKitty

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.