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.

One Comment

  1. noah

    Should the title be “Binary *search* an array in JavaScript”?

Leave a Comment

Enclose code in <code lang="ruby"></code> if you care.
Preview your comment using the button below.