Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/454.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么我的javascript二进制搜索出错?_Javascript_Algorithm - Fatal编程技术网

为什么我的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]

我用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;
}
这是一把小提琴。
您的比较是反向的。如果在
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));