Skip to content

Instantly share code, notes, and snippets.

@steverydz
Last active April 9, 2018 09:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steverydz/e7ddb319e3f66cad90ca27a80ccb2672 to your computer and use it in GitHub Desktop.
Save steverydz/e7ddb319e3f66cad90ca27a80ccb2672 to your computer and use it in GitHub Desktop.
JavaScript binary search algorithm
function binarySearch(list, item) {
var low = 0;
var high = list.length - 1;
while (low <= high) {
var mid = low + Math.floor((low + high) / 2);
var guess = list[mid];
if (guess === item) {
return mid;
}
if (guess > item) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment