Since you are supposed to be doing this for your learning, I don't think anyone will just hand you the code you want, but here's a description of a binary search:
  1. Keep a high and a low index into the array that demarcate the possible range that may contain your sought word. Initially, the low index is 0 and the high index is the last index of the array, or -1 if the array is empty.
  2. See if the high index is at least as great as the low index (i.e. the possible range of the array that might contain the sought word is not empty). If not, the sought word is not in the array and you are done.
  3. Find the midpoint between the high and low indexes, rounding either up or down.
  4. If the word at the midpoint index is greater than (using a string comparison) the sought word, the sought word must occur earlier in the array, if at all. Set the high index to one less than the midpoint index, and continue at step 2.
  5. Otherwise, if the word at the midpoint index is less than (using a string comparison) the sought word, the sought word must occur later in the array, if at all. Set the low index to one more than the midpoint index, and continue at step 2.
  6. Otherwise, the sought word is at the midpoint index: you've found it and are done.
A common variation is to have the "high" index be one more than the highest possible index.

Test well; it's very common for people writing binary search code to have off-by-one errors that result in false negatives or endless loops.


In reply to Re: Check word presence WITHOUT hashes or grep by ysth
in thread Check word presence WITHOUT hashes or grep by gojippo

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.