Skip to content

Instantly share code, notes, and snippets.

@katspaugh
Created June 10, 2011 08:51
Show Gist options
  • Save katspaugh/1018499 to your computer and use it in GitHub Desktop.
Save katspaugh/1018499 to your computer and use it in GitHub Desktop.
Binary search
Array.prototype.bsearch = function (x) {
var min = 0, max = this.length;
while (min <= max) {
var mid = Math.floor((min + max) / 2),
val = this[mid];
if (val === x) {
return mid;
}
if (x > val) {
min = mid + 1;
} else {
max = mid - 1;
}
}
return -1;
};
var Letters = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ];
alert(Letters.bsearch('A'));
alert(Letters.bsearch('K'));
alert(Letters.bsearch('Z'));
alert(Letters.bsearch('Ъ'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment