I wrote an implementation of binary search in JavaScript earlier for kicks, but I noticed my version was significantly different than those found on Google. Here is an example of binary search I found on Google (copied here to combat link rot):
Array.prototype.binarySearch = function(find, comparator) {
var low = 0, high = this.length - 1,
i, comparison;
while (low <= high) {
i = Math.floor((low + high) / 2);
comparison = comparator(this[i], find);
if (comparison < 0) { low = i + 1; continue; };
if (comparison > 0) { high = i - 1; continue; };
return i;
}
return null;
};
Most of the other implementations on Google are quite similar. But in mine, I don't subtract one from the low/high and continue from there. Instead, I divide the array in half and continue dividing the appropriate side in half until I reach the proper value. Code:
function binary_search_iterative(arr, ele) {
var beginning = 0, end = arr.length,
target;
while (true) {
target = Math.floor((beginning + end) / 2);
if ((target === end || target === beginning) && arr[target] !== ele) {
return -1;
}
if (arr[target] > ele) {
end = target;
} else if (arr[target] < ele) {
beginning = target;
} else {
return target;
}
}
}
I wrote this recursive-style as well, but in testing I found this iterative version was faster.
In my tests, I've found that the examples I've found on Google (though they did not include the one above, they were nearly identical) are faster on smaller arrays, but as the input size increases, mine overtakes those. Since binary searches are usually limited (?) to larger input sizes, I see this as an improvement.
Is my thinking correct? Could this be done in an even better way?
I also do not like this:
if ((target === end || target === beginning) && arr[target] !== ele) {
return -1;
}
And I was curious if there is a good way to eliminate it or refactor the function where it's cleaner in general.