Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re^3: Binary search

by golux (Hermit)
on Mar 29, 2013 at 17:39 UTC ( #1026179=note: print w/replies, xml ) Need Help??

in reply to Re^2: Binary search
in thread Binary search

Hi akvats01,

Did you try printing out the sorted list to make sure it got sorted correctly?

I did, and got:

print "Sorted => @num_list\n"; # Output: Sorted => 34 2 65 345 987 23 12 45 62 100

So the sort isn't working. Now that I know that's a problem, I look at your sort line more carefully:

@num_list= sort {a <=> b} @num_list1;
And it's obvious what's wrong; you should use "$a" and "$b". You would have found that if you used the "strict" and "warnings" pragmas. Try running this partial program and you'll see:
#!/usr/bin/perl use strict; use warnings; my @num_list1=(34,2,65,345,987,23,12,45,62,100); my @num_list= sort {a <=> b} @num_list1; print "Sorted: @num_list\n"; # Output: # # Bareword "a" not allowed while "strict subs" in use at li +ne 7. # Bareword "b" not allowed while "strict subs" in use at li +ne 7. # Execution of aborted due to compilation errors.
The other (potential) problem I can see is that you are not doing integer math, so when you take the average of $low and $high with:
$mid = ($low+$high)/2;
you're sometimes getting a fractional result. You may need to use int to fix that.

Try those fixes to start with and see if you can get farther. One other recommendation would be to put print statements at various locations in your code to make sure you're getting the expected results each time through the loop.

say  substr+lc crypt(qw $i3 SI$),4,5

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1026179]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (8)
As of 2017-07-28 10:19 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (427 votes). Check out past polls.