use strict;
use warnings;
my @allwords = sort qw(array will be the sorted wordlist and target);
sub binary_search {
my ($array, $target) = @_;
#set arguments for future use : $array will be the sorted wordlist
+ and $target, the word we will be looking for.
my ($low, $high) = (0, @$array - 1);
#Declare high and low indexes. Low index = 0 and high index = last
+ index of the array.
while ($low < $high)
{ # If high index is higher than the low index, keep the window
+ open.
my $cur =
int ($low + $high) / 2
; #Declare a middle, which is the total of high index and
+low index /2.
if ($array->[$cur] lt $target) {
$low = $cur + 1; #If the target is too small, try lower
+.
} else {
$high = $cur; #Else, try higher.
}
}
}
for my $word (qw (search wordlist)) {
my $index = binary_search (\@allwords, $word);
next if $index >= @allwords;
if ($allwords[$index] eq $word) {
print "Found $word at $index\n";
} else {
print "Couldn't find $word\n";
}
}
Prints:
Couldn't find search
Couldn't find wordlist
which seems to indicate that your search is failing.
For any non-trivial project you would take the test code and wrap it up in something like Test::More as a unit test so that you have a convenient way to test all the edge cases (zero, one or two words in the list for example) whenever you alter the code.
Perl is environmentally friendly - it saves trees
|