Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Comment on


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

and:  <code> code here </code>

  • Please read these before you post! —
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others scrutinizing the Monastery: (6)
    As of 2014-12-27 11:37 GMT
    Find Nodes?
      Voting Booth?

      Is guessing a good strategy for surviving in the IT business?

      Results (177 votes), past polls