二进制搜索算法 - 无限循环

时间:2017-12-11 15:04:01

标签: javascript algorithm search binary-search

我的二进制搜索算法存在问题。我试图在javascript中实现它,但它仍然得到一个无限循环。这是我的代码:

var a = [1, 4, 5, 8, 11, 15]

function binarySearch(arr, item){
  let low = 0
  let high = arr.length - 1

  while(low <= high) {
    var m = (low + high)/2 | 0
    if(arr[m] == item){
        console.log("Item found in index: " + m)
      return false;
    } else {
            if(a[m] > item){
            console.log("Too high")
          h = m - 1
        } else {
            console.log("Too low")
          l = m + 1
        }
    }
  }
  console.log("Item not found")
  return false;
}

binarySearch(a, 1)

1 个答案:

答案 0 :(得分:2)

尝试执行此操作(修改了您的代码中的某些错误):

var a = [1, 4, 5, 8, 11, 15]

function binarySearch(arr, item) {
    var low = 0
    var high = arr.length - 1

    while (low <= high) {
        let m = low + (high - low ) / 2
        if (arr[m] == item) {
            console.log("Item found in index: " + m)
            return false;
        }
        if(a[m] > item) {
            console.log("Too high")
            hight = m - 1
        } else {
            console.log("Too low")
            low = m + 1
        }
    }
    console.log("Item not found")
    return false;
}

binarySearch(a,1)