Created
March 14, 2013 09:11
-
-
Save jonathanmarvens/5159969 to your computer and use it in GitHub Desktop.
Binary search in multiple languages...
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
function binarySearch (key, array) { | |
var low = 0; | |
var high = (array.length - 1); | |
while (low <= high) { | |
var mid = floor(((low + high) / 2)); | |
var val = array[mid]; | |
if (val < key) { | |
low = (mid + 1); | |
} else if (val > key) { | |
high = (mid - 1); | |
} else { | |
return mid; | |
} | |
} | |
return null; | |
} |
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
def binary_search (key, array): | |
low = 0 | |
high = (len(array) - 1) | |
while low <= high: | |
mid = int(((low + high) / 2)) | |
value = array[mid] | |
if value < key: | |
low = (mid + 1) | |
elif value > key: | |
high = (mid - 1) | |
else: | |
return mid | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment