Skip to content

Instantly share code, notes, and snippets.

@ngryman
Created July 18, 2012 18:10
Show Gist options
  • Save ngryman/3137817 to your computer and use it in GitHub Desktop.
Save ngryman/3137817 to your computer and use it in GitHub Desktop.
javascript binarySearch
Array.prototype.binarySearch = function(key) {
var low = 0,
high = this.length - 1;
while (low <= high) {
var mid = (low + high) >>> 1;
var midVal = this[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment