Skip to content

Instantly share code, notes, and snippets.

@bennetthardwick
Created January 24, 2018 13:53
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 bennetthardwick/a58e03801d9fffa9157f1cb475b8c442 to your computer and use it in GitHub Desktop.
Save bennetthardwick/a58e03801d9fffa9157f1cb475b8c442 to your computer and use it in GitHub Desktop.
A binary search in JavaScript!
Array.prototype.bsearch = function(value) {
let array = this;
let low = 0;
let high = array.length - 1;
while (low <= high) {
let mid = Math.ceil((low + high) / 2);
if (array[mid] > value) high = mid - 1;
else if (array[mid] < value) 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