Created
October 23, 2010 22:40
-
-
Save robinator/642786 to your computer and use it in GitHub Desktop.
Binary search implemented in coffeescript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
binary_search = (val, L) -> | |
return false if L.length == 0 | |
mid = Math.floor(L.length / 2) | |
if L[mid] == val | |
return mid | |
else if val > L[mid] | |
binary_search(val, L[(mid + 1)..(L.length)]) | |
else | |
binary_search(val, L[0..(mid - 1)]) | |
list = [1,2,3,4,5,6,7,8] | |
alert binary_search(18, list) # false | |
alert binary_search(3, list) # 2 | |
alert binary_search(6, list) # 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wouldn't line 5's
return mid
just constantly return 1?Here's an example at each level:
Assume val = 2
mid = floor ( 9 / 2 ) = 4
mid = floor ( 4 / 2 ) = 2
mid = floor ( 2 / 2 ) = 1
if L[mid] == val matches and we now return 1