javascript - 为什么我的 javascript 二进制搜索出错?

标签 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;
}

虽然在我的整数数组中找不到 5,但失败了。

var intArray = [1, 2, 3, 5]

if (intArray.binarySearch(5))
  alert("found!");
else 
  alert("no found!");

这是一个 fiddle 。 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));

关于javascript - 为什么我的 javascript 二进制搜索出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9713270/

相关文章:

javascript - 如何删除字符串第一个位置和最后一个位置的逗号(,)

c - 如何编写一个 C 程序来检查一个点是否位于给定其对角线之一的端点的正方形内

algorithm - 在二维网格上创建随机形式

java - 为什么我们要在一些递归算法中复制一个ArrayList?

algorithm - 分而治之斐波那契程序的运行时间

javascript - 根据复选框检查从另一个数组中删除数组

javascript - 使用 AJAX 将表单输入发送到 PHP

javascript - React TypeScript Web 动画 API - 对象可能是 'null'

javascript - session 如何在 Express.js 和 Node.js 中工作?

algorithm - 任何线性算法的 Big Omega 是 n 还是也可以是 1?