Yes, stick with the binary search. Just change the terminating condition from

$query == $array->[$center]

to

$query == $array->[$center] && ($begin ? ($center == 0 || $query != $array->[$center-1]) : ($center == $#$array || $query != $array->[$center+1]) )

You check the condition a second and third time later down, so you need to fix those too.

All together:

sub binarySearch { my ($begin, $query, $array) = @_; return 0 if $query < $array->[0] and $begin == 1; return $#$array if $query > $array->[$#$array] and $begin == 0; my ($left, $right, $prevCenter) = (0, $#$array, -1); while(1) { my $center = int (($left + $right)/2); my $cmp = $query <=> $array->[$center] || ($begin ? ($center == 0 || $query != $array->[$center- +1] ? 0 : -1) : ($center == $#$array || $query != $array->[$center+ +1] ? 0 : +1) ); return $center if $cmp == 0; if ($center == $prevCenter) { return $right if $begin == 1; return $right-1 if $begin == 0; } $right = $center if $cmp < 0; $left = $center if $cmp > 0; $prevCenter = $center; } }

Update: Added code.


In reply to Re^3: My Binary Search Perl code takes forever by ikegami
in thread My Binary Search Perl code takes forever by Anonymous Monk

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.