Array.prototype.binarySearch = function binarySearch(find, comparator) { var low = 0, high = this.length - 1, i, comparison; while (low <= high) { i = parseInt((low + high) / 2, 10); comparison = comparator(this[i], find); if (comparison < 0) { low = i + 1; continue; }; if (comparison > 0) { high = i - 1; continue; }; return i; } return null; };
Extending Array with this binarySearch method allows you to re-use the functional arguments to passed to sort to generate the sorted array in the first place.
Should the title be “Binary *search* an array in JavaScript”?
January 21st, 2009