Skip to content

Instantly share code, notes, and snippets.

@clippit
Created November 5, 2012 11:53
Show Gist options
  • Save clippit/4016851 to your computer and use it in GitHub Desktop.
Save clippit/4016851 to your computer and use it in GitHub Desktop.
binary search
var find = function(arr, key) {
if (arr.length < 1) {
return null;
}
var low = 0,
high = arr.length - 1,
middle;
while(high >= low) {
middle = Math.floor((low + high) / 2);
//console.log(low, middle, high);
value = arr[middle];
if (value == key) {
return middle;
} else if (value < key) {
low = middle + 1;
} else {
high = middle - 1;
}
}
return -1;
}
@kavinyao
Copy link

kavinyao commented Nov 5, 2012

why not value === key?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment