I am beginner in perl.
I have implemented binary search for leaning purpose. The code shows abrupt results. For few items in the list, it returns the exact position, but it is not able to find out the position of other elements especially towards the end of array.
Like the Key is 2,65 etc the result is 1 but if the key is 34,100,or 42 etc the result is : not found
I wonder, if this code is not working it should not work for any thing. Please tell me where am I wrong.
Code :
#!/usr/bin/perl @num_list=(34,2,65,345,987,23,12,45,62,100); $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 "Not found";}
In reply to Binary search by akvats01
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |