Javascript Array binarySearch(target, comparator)
/*/* ww w. j a v a2s . c o m*/ target: the object to search for in the array comparator: (optional) a method for comparing the target object type return value: index of a matching item in the array if one exists, otherwise the bitwise complement of the index where the item belongs */ Array.prototype.binarySearch = function (target, comparator) { var l = 0, h = this.length - 1, m, comparison; comparator = comparator || function (a, b) { return (a < b ? -1 : (a > b ? 1 : 0)); /* default comparison method if one was not provided */ }; while (l <= h) { m = (l + h) >>> 1; comparison = comparator(this[m], target); if (comparison < 0) { l = m + 1; } else if (comparison > 0) { h = m - 1; } else { return m; } } return~l; };