Home  |  Linux  | Mysql  | PHP  | XML
From:rich lee Date:Sat Jun 27 17:00:19 2009
Subject:help on example from "mastering algorithm with perl" on binary search
Hello everyone,

I am trying to read "mastering algorithm with perl" and below example has me
bit stuck.
I understand everything except these 2 lines


$low = $try + 1, next if $array->[$try] lt $word;
$high = $try -1, next if $array->[$try] gt $word;

I understand what it's doing but I am not sure how they are being ran.
For example, Let's say in one particular turn, $array->[$try] is greater
than $word...
I am trying to understand how it skips this line ---> $low = $try + 1, next
if $array->[$try] lt $word;

when I look at above 2 lines, it looks like they should be processed
sequentially. Meaning $low = $try + 1 should be processed everytime...and
$high=$try-1 should be
processed everytime....

In reality(after looking at the explanation), it should only lower or raise
when $array->[$try] is either less than(then it should raise the bottom) and
greater( should lower the top)
I think I am just not understanding the syntax on above 2 lines.. can
someone please describe it for me(or am i missing the precedence of the
relationship of the line??


$index = binary_search( \@array, $word )

sub binary_search {
my ($array, $word) = @_;
my ($low, $high) = ( 0, @$array - 1 );

while ( $low <= $high ) {
my $try = int( ($low+$high)/2 );
$low = $try + 1, next if $array->[$try] lt $word;
$high = $try -1, next if $array->[$try] gt $word;

return $try; #we've found the word!
}
return; #the word isn't there
}

Navigate in group perl.beginners at sever nntp.perl.org
Previous Next


Your recent visits
Re: Manipulating the symbol table
script for shutdown remote machine
Traversing Hash printing two times
Re: Need help with Mail::Sender
Re: Traversing Hash printing two times



  
© No Copyright
You are free to use Anything, but please consult your advocate before doing so as this website
also list content from other sources which may be copyrighted.
Site Maintained by Zareef Ahmed
Powered By PHP Consultants