Skip to content

Instantly share code, notes, and snippets.

@jonathanmarvens
Created March 14, 2013 09:11
Show Gist options
  • Save jonathanmarvens/5159969 to your computer and use it in GitHub Desktop.
Save jonathanmarvens/5159969 to your computer and use it in GitHub Desktop.
Binary search in multiple languages...
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;
}
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