#!/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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Binary search algorithm.
by ikegami (Patriarch) on Aug 13, 2011 at 04:56 UTC | |
|
Re: Binary search algorithm.
by afoken (Chancellor) on Aug 13, 2011 at 05:11 UTC | |
by jwkrahn (Abbot) on Aug 13, 2011 at 05:33 UTC | |
by ikegami (Patriarch) on Aug 13, 2011 at 06:00 UTC | |
|
Re: Binary search algorithm.
by jwkrahn (Abbot) on Aug 13, 2011 at 05:14 UTC | |
by ikegami (Patriarch) on Aug 13, 2011 at 05:18 UTC | |
by jwkrahn (Abbot) on Aug 13, 2011 at 05:36 UTC | |
by ikegami (Patriarch) on Aug 13, 2011 at 05:54 UTC | |
by jwkrahn (Abbot) on Aug 13, 2011 at 06:17 UTC | |
|