in reply to My Binary Search Perl code takes forever
#!/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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: My Binary Search Perl code takes forever
by Anonymous Monk on Jun 11, 2009 at 10:46 UTC |