Skip to content

Instantly share code, notes, and snippets.

@mohnish
Last active October 1, 2022 04:24
Show Gist options
  • Save mohnish/a83e5bfab2b884fafa9717ea1066c6c4 to your computer and use it in GitHub Desktop.
Save mohnish/a83e5bfab2b884fafa9717ea1066c6c4 to your computer and use it in GitHub Desktop.
Binary Search in JavaScript
function binarySearch(list, key) {
let low = 0;
let high = list.length - 1;
while (low <= high) {
let mid = low + Math.floor((high - low) / 2);
if (key < list[mid]) {
high = mid - 1;
} else if (key > list[mid]) {
low = mid + 1;
} else {
return mid;
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment