我正在尝试使用 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]);
冉冉说
MM们
相关分类