dan*_*007 0 javascript algorithm
我用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;
}
Run Code Online (Sandbox Code Playgroud)
虽然在我的整数数组中找到5但它失败了.
var intArray = [1, 2, 3, 5]
if (intArray.binarySearch(5))
alert("found!");
else
alert("no found!");
Run Code Online (Sandbox Code Playgroud)
这是一个小提琴. http://jsfiddle.net/3uPUF/3/
你有向后改变低和高的逻辑,if this[i] > find然后你想看1和i-1之间.If this[i] < find那么你想看看i + 1和数组的长度.
尝试进行这些更改:
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) { return i; };
if (this[i] > find) { high = i - 1;};
if (this[i] < find) { low = i + 1;};
}
return null;
}
var intArray = [1, 2, 3, 5]
//index of the element in the array or null if not found
alert(intArray.binarySearch(5));
Run Code Online (Sandbox Code Playgroud)