Anonymous Monk,
I wrote the following code without having looked at yours just to see how long it took:
#!/usr/bin/perl use strict; use warnings; my @array = 1 .. 3_141_592; for (1 .. 400) { my $idx = bin_search(\@array, int(rand 3_141_592) + 1); } sub bin_search { my ($list, $tgt) = @_; return 0 if $tgt < $list->[0]; return $#$list if $tgt > $list->[-1]; my ($beg, $end, $val) = (0, $#$list, undef); while ($beg <= $end) { my $mid = int(($beg + $end) / 2); $val = $list->[$mid]; if ($val > $tgt) { $end = $mid - 1; } elsif ($val < $tgt) { $beg = $mid + 1; } else { return $mid; } } return -1; }

It takes less than 1.5 seconds to run. Additionally, it takes almost exactly the same time if I don't run the bin_search(). In other words, the 400 searches take a negligible amount of time and the majority of the 1.5 seconds is building the array.

Now that I have looked at your code, I recognize it doesn't do everything you want. Modifying it shouldn't be difficult. Elsewhere in the thread you mention duplicates. If this array needs to be searched many times and will not change between searches, perhaps you should hash the index of the first position of each unique integer. Without knowing more about the problem - it is hard to offer optimization suggestions.

Cheers - L~R


In reply to Re: My Binary Search Perl code takes forever by Limbic~Region
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.