My implementation:
Array.prototype.binarySearchFast = function(search) {
var size = this.length,
high = size -1,
low = 0;
while (high > low) {
if (this[low] === search) return low;
else if (this[high] === search) return high;
target = (((search - this[low]) / (this[high] - this[low])) * (high - low)) >>> 0;
if (this[target] === search) return target;
else if (search > this[target]) low = target + 1, high--;
else high = target - 1, low++;
}
return -1;
};
Normal Implementation:
Array.prototype.binarySearch = function(find) {
var low = 0, high = this.length - 1,
i, comparison;
while (low <= high) {
i = Math.floor((low + high) / 2);
if (this[i] < find) { low = i + 1; continue; };
if (this[i] > find) { high = i - 1; continue; };
return i;
}
return null;
};
The difference being my implementation makes a guess at the index of the value based on the values at the start and end positions instead of just going straight to the middle value each time.
I wondered if anyone could think of any case scenarios where this would be slower than the original implementation.
UPDATE: Sorry for the bad examples. I have now made them a little easier to understand and have setup some tests on jsPerf. See here:
http://jsperf.com/binary-search-2
I'm seeing about 75% improvement by using my method.