Advertisement
zinch

Binary Search

Aug 18th, 2014
497
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.00 KB | None | 0 0
  1. #!/usr/bin/perl
  2. #
  3. #bsearch - search for a word in a list of alphabetically ordered words
  4. #Usage: bsearch word filename
  5.  
  6. $word = shift;
  7. @array = <>;
  8.  
  9. ($word, @array) = map { lc } ($word, @array);
  10. @array = map { s/(\n|\r)+// && $_ } @array;
  11. $index = binary_search(\@array, $word);
  12.  
  13. if (defined($index)) {
  14.     print "{$word} occurs at position $index.\n";
  15. } else {
  16.     print "{$word} doesn't occur.\n";
  17. }
  18.  
  19. # $index = binary_search( \@array, $word )
  20. #  @array is a list of lowercase strings in alphabetical order.
  21. #  $word is the target word that might be in the list.
  22. #  binary_search() returns the array index such that $array[$index]
  23. #  is $word.
  24.  
  25. sub binary_search {
  26.     my ($array, $word) = @_;
  27.     my ($low, $high) = (0, @$array - 1);
  28.    
  29.     while ( $low <= $high) {
  30.     my $try = int( ($low + $high)/2 );
  31.     print "DEBUG:$try {$array->[$try]}\n";
  32.     $low = $try + 1, next if $array->[$try] lt $word;
  33.     $high = $try - 1, next if $array->[$try] gt $word;
  34.     return $try;
  35.     }
  36.     return;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement