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

时间:2012-03-15 02:39:39

标签: 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!");

这是一个小提琴。 http://jsfiddle.net/3uPUF/3/

2 个答案:

答案 0 :(得分:6)

你有向后改变低和高的逻辑,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));

答案 1 :(得分:3)

您的比较是倒退的。如果在i找到的项目大于您要查找的内容,则需要调整high,而不是low。查看我的updated jsFiddle

相关问题