Created
July 18, 2012 18:10
-
-
Save ngryman/3137817 to your computer and use it in GitHub Desktop.
javascript binarySearch
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.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