I wrote a binary search in javascript.
Array.prototype.binarySearch = function(find) {
var low = 0, high = this.length - 1,
i;
while (low <= high) {
i = Math.floor((low + high) / 2);
if (this[i] > find) { low = i; continue; };
if (this[i] < find) { high = i; continue; };
return i;
}
return null;
}
It fails though to find 5 in my array of integers.
var intArray = [1, 2, 3, 5]
if (intArray.binarySearch(5))
alert("found!");
else
alert("no found!");
Here is a Fiddle. http://jsfiddle.net/3uPUF/3/
thisfromthis[i]Array.prototype.binarySearch? Why doesn'tArray.binarySearchwork?(low + high) / 2withlow + (high - low) / 2to avoid overflowArrayas just a function that makes new arrays; the new arrays delegate toArray.prototypeand not toArray. that's just how it works.