【问题标题】:Binary Search Algorithmn - infinity loop二分搜索算法 - 无限循环
【发布时间】:2020-05-16 23:02:18
【问题描述】:

我的二分搜索算法有问题。我正在尝试在 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)

【问题讨论】:

  • 您应该先Math.floorMath.ceil 将值(low + high) / 2 分配给m。你应该使用相同的变量lowhighlh,而不是两者。
  • while(low &lt;= high) 你实际上并没有在循环中修改这些变量中的任何一个,所以如果条件开始为真,它永远不会变为假。
  • 好的,谢谢,我没有注意到我使用“l”和“h”而不是“low”和“high”。现在它正在工作,非常感谢。顺便提一句。 Math.floor 的工作方式与 | 相同0
  • @sh3ev,不,按位或将数字先转换为 32 位,然后再转换回 64 位浮点数,而 Math.floor 将数字保持在 64 位浮点数。

标签: javascript algorithm search binary-search


【解决方案1】:

试试这个(从您的代码中编辑了一些错误):

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 2015-12-17
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    相关资源
    最近更新 更多