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



我用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));

您的比较是向后的。如果在i中找到的项目大于您要查找的项目,则需要调整high,而不是low。查看我更新的jsFiddle。

最新更新