Created
January 24, 2018 13:53
-
-
Save bennetthardwick/a58e03801d9fffa9157f1cb475b8c442 to your computer and use it in GitHub Desktop.
A binary search in JavaScript!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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