为什么这种二进制搜索实现会使浏览器无响应?

时间:2015-06-09 15:42:11

标签: javascript arrays binary-search

我在Chrome控制台中尝试过二进制搜索。但是当我运行代码时,整个Chrome被绞死了,我不得不杀死这些页面:

var arr = [1, 3, 5, 8];
var binary = function (arr, search) {

    var low = 0;
    var high = arr.length - 1;
    var mid = (high + low) / 2;
    while (low <= high) {

        if (search === arr[mid]) {

            return mid;
        } else if (search > arr[mid]) {
            low = mid + 1;

        } else {
            high = mid - 1;
        }

    }
    return -1;
};

console.log(binary(arr, 3));

2 个答案:

答案 0 :(得分:4)

问题出在这一行

var mid = (high + low) / 2;

由于mid是浮点值,arr[mid]始终返回undefined。您可以像这样确认这个

var arr = [1, 3, 5, 8];
console.log(arr[1.5]);
// undefined

<强>解决方案

  1. 要解决此问题,您可以将其转换为整数,例如

    var mid = parseInt((high + low) / 2, 10);
    
  2. 正如Rick在评论中所指出的,mid计算必须在while循环中进行。因此,while循环看起来像这样

    while (low <= high) {
        mid = parseInt((high + low) / 2, 10);
        if (search === arr[mid]) {
            return mid;
        } else if (search > arr[mid]) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    

答案 1 :(得分:1)

在您的代码中,mid 总是 1.5,因为它是在循环之前计算的。

相反,在循环中移动mid计算,并将其计算为highlow的舍入平均值:

var arr = [1, 3, 5, 8];
var binary = function(arr, search) {

  var low = 0;
  var high = arr.length - 1;
  var mid;

  while (low <= high) {
    mid = Math.round((high + low) / 2);
    if (search === arr[mid]) {
      return mid;
    } else if (search > arr[mid]) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }
  return -1;
};

console.log(binary(arr, 3)); //1
console.log(binary(arr, 8)); //3
console.log(binary(arr, 17)); //-1