in reply to Binary search algorithm.

my @array = @$arrayref; my $word = $$wordref;

Why copy all this data?    Why not just use $arrayref $wordref directly?



while ($lo <= :w $hi) {

What is the meaning of :w in the code?    That looks like a syntax error.



$lo = ++$try; # without increment there will be ... $hi = --$try;

Why are you modifying $try?    It always gets assigned from int(($lo + $hi)/2) at the top of the loop.



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 }

The use of next is superfluous because of the way that if elsif else works.

Replies are listed 'Best First'.
Re^2: Binary search algorithm.
by ikegami (Patriarch) on Aug 13, 2011 at 05:18 UTC

    What is the meaning of :w in the code?

    :w is vi's save ("write") command. He must have tried to save while in edit mode.

    Why are you modifying $try? It always gets assigned from int(($lo + $hi)/2) at the top of the loop.

    Yes, but $hi or $lo changes in every loop pass.

      Yes, but $hi or $lo changes in every loop pass.

      Yes but that doesn't mean you have to modify $try.

        Yes, it does. The algorithm is: Find the halfway point ($try) of the area to search ($lo..$hi). Find in which half the result lies. Repeat.