http://www.perlmonks.org?node_id=1026173


in reply to Re: Binary search
in thread Binary search

Thanks to everyone. I have sorted the array as follows

@num_list1=(34,2,65,345,987,23,12,45,62,100); @num_list= sort {a <=> b} @num_list1;
Still the same results are shown. I am due to go through the algorithm implementation mentioned above. Meanwhile, I will be thankful if some light may be thrown on why the code is working partially? what precautions should I take to avoid this situation when code is working partially. Thanks.

My apologies for code not being readable. The original code, after implementing sort is :

#!/usr/bin/perl @num_list1=(34,2,65,345,987,23,12,45,62,100); @num_list= sort {a <=> b} @num_list1; $low=0; $found_key=0; $index; $high=$#num_list; print "enter the key: \t"; chomp($key=<STDIN>); while($high>=$low && !$found_key) { $mid=($low+$high)/2; if ($key == @num_list[$mid]) { $found_key=1; $index = int($mid); } if ($key > @num_list[$mid]) { $low = $mid+1; } if ($key < @num_list[$mid]) { $high = $mid-1; } } if ($found_key) { print " The key is $index\n"; } else {print "key is not found";}