Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^3: Binary search

by golux (Pilgrim)
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 1026159.pl li +ne 7. # Bareword "b" not allowed while "strict subs" in use at 1026159.pl li +ne 7. # Execution of 1026159.pl 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


Comment on Re^3: Binary search
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1026179]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2014-09-03 07:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (35 votes), past polls