#!/usr/bin/perl use strict; use warnings; use 5.010; use lib '/home/kaiyin/perl5/mylib'; sub BinSearch { my ($arrayref, $wordref) = @_; my @array = @$arrayref; my $word = $$wordref; my ($lo, $hi) = (0, $#array); while ($lo <= :w $hi) { my $try = int(($lo + $hi)/2); if ($array[$try] lt $word) { $lo = ++$try; # without increment there will be # a dead loop in the 4th case, # see the note at the bottem next } elsif ($array[$try] gt $word) { $hi = --$try; next } else { return $try } } return; } my @a = qw(format type ascii hex pos len binary search perl unix eof a +rray word); my @a = sort @a; my $w = "len"; say "@a"; say BinSearch(\@a, \$w); # There are only 5 cases to consider: # * - - # - * - trivial # - - * # - * # * - trivial # # Among which 2 are trivial, that is to say # $array[$try] will immediately match $word
Binary search algorithm.
In reply to Binary search algorithm. by kindlychung
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |