为什么我的javascript二进制搜索出错?
我用javascript编写了一个二进制搜索为什么我的javascript二进制搜索出错?,javascript,algorithm,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]
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;
}
这是一把小提琴。
您的比较是反向的。如果在
i
找到的项目大于您要查找的项目,则您希望调整高
,而不是低
。请参见my。您有更改低和高的逻辑,如果此[i]>查找,则您希望查看1和i-1之间的值如果此[i]
,则您希望在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));
Array.prototype.binarySearch=函数(查找){
var low=0,high=this.length-1,
我
while(low-find){high=i-1;};
如果(这个[i]
在小提琴中,你错过了这个[i]
中的这个
,谢谢。我没有注意到这一点。另外,为什么我必须用Array.prototype.binarySearch
定义方法?为什么Array.binarySearch
不起作用?可能需要将(低+高)/2
替换为low+(高-低)/2
以避免溢出阅读cockburn的《好零件》一书。基本上,这就是语言寻找这些东西的地方。把Array
看作是一个生成新数组的函数;新数组委托给Array.prototype
,而不是Array
。这就是它的工作原理。
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));