猿问

二分查找总是返回 -`

我正在尝试使用 JS 实现二进制搜索,但它进入了无限循环。它不会返回位置。我不确定我在做什么错误。


代码:


function binarySearch(value, list) {

    let initial = 0;

    let end = list.length - 1;

    let found = false;

    let middle;

    let position = -1;

  

    while (found != true && initial <= end){

      middle = Math.round(initial + end) / 2;

      if (value == list[middle]) {

      found = true;

      position = middle;

      } else if (value < list[middle]) end = middle - 1;

      else initial = middle + 1;

  }

      console.log(position) ;

  

  }

binarySearch(3, [1, 3, 5, 6]);


莫回无
浏览 77回答 2
2回答

冉冉说

你有middle = Math.round(initial + end) / 2;which 并不总是导致整数。将其更改middle = Math.round((initial + end) / 2);为始终获取整数。

MM们

下面的代码总是正确的,因此是一个无限循环。while (found != true && initial <= end)&nbsp; &nbsp; middle = Math.round(initial + end) / 2;将代码放在大括号内function binarySearch(value, list) {&nbsp; let initial = 0;&nbsp; let end = list.length - 1;&nbsp; let found = false;&nbsp; let middle;&nbsp; let position = -1;&nbsp; while (found != true && initial <= end){&nbsp; &nbsp; middle = Math.round((initial + end) / 2);&nbsp; &nbsp; if (value == list[middle]) {&nbsp; &nbsp; found = true;&nbsp; &nbsp; position = middle;&nbsp; &nbsp; } else if (value < list[middle]) end = middle - 1;&nbsp; &nbsp; else initial = middle + 1;}&nbsp; &nbsp; return position;i}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答