Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- #
- #bsearch - search for a word in a list of alphabetically ordered words
- #Usage: bsearch word filename
- $word = shift;
- @array = <>;
- ($word, @array) = map { lc } ($word, @array);
- @array = map { s/(\n|\r)+// && $_ } @array;
- $index = binary_search(\@array, $word);
- if (defined($index)) {
- print "{$word} occurs at position $index.\n";
- } else {
- print "{$word} doesn't occur.\n";
- }
- # $index = binary_search( \@array, $word )
- # @array is a list of lowercase strings in alphabetical order.
- # $word is the target word that might be in the list.
- # binary_search() returns the array index such that $array[$index]
- # is $word.
- sub binary_search {
- my ($array, $word) = @_;
- my ($low, $high) = (0, @$array - 1);
- while ( $low <= $high) {
- my $try = int( ($low + $high)/2 );
- print "DEBUG:$try {$array->[$try]}\n";
- $low = $try + 1, next if $array->[$try] lt $word;
- $high = $try - 1, next if $array->[$try] gt $word;
- return $try;
- }
- return;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement