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

问题描述 投票:0回答:1

我的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)
javascript algorithm search binary-search
1个回答
0
投票
var a = [1, 4, 5, 8, 11, 15]

function binarySearch(arr, item){
  let low = 0
  let 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;
    } else {
        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)

© www.soinside.com 2019 - 2024. All rights reserved.