Skip to content

Instantly share code, notes, and snippets.

@joshbedo
Created July 9, 2015 16:24
Show Gist options
  • Save joshbedo/056429fcb7bfd00a53f3 to your computer and use it in GitHub Desktop.
Save joshbedo/056429fcb7bfd00a53f3 to your computer and use it in GitHub Desktop.
Binary Search
var list = [1,4,8,10,23,26,55,77,88];
var binarySearch = function(key) {
var low = 0;
var high = list.length - 1;
while(low <= high) {
var mid = Math.floor(low + (high - low) / 2);
if (key < list[mid]) {
high = mid - 1;
} else if (key > list[mid]) {
low = mid + 1;
} else {
return mid;
}
}
return -1;
}
// Returns index of N, if not found returns -1
console.log(binarySearch(4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment