akvats01 has asked for the wisdom of the Perl Monks concerning the following question:
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";}
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Binary search
by moritz (Cardinal) on Mar 29, 2013 at 15:05 UTC | |
|
Re: Binary search
by davido (Cardinal) on Mar 29, 2013 at 16:33 UTC | |
|
Re: Binary search
by LanX (Saint) on Mar 29, 2013 at 15:09 UTC | |
|
Re: Binary search
by akvats01 (Initiate) on Mar 29, 2013 at 16:50 UTC | |
by roboticus (Chancellor) on Mar 29, 2013 at 19:41 UTC | |
by akvats01 (Initiate) on Mar 29, 2013 at 17:04 UTC | |
by golux (Chaplain) on Mar 29, 2013 at 17:39 UTC | |
by farang (Chaplain) on Mar 29, 2013 at 17:41 UTC |