我正在尝试使用 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]);
2 回答
冉冉说
TA贡献1877条经验 获得超1个赞
你有middle = Math.round(initial + end) / 2;
which 并不总是导致整数。
将其更改middle = Math.round((initial + end) / 2);
为始终获取整数。
MM们
TA贡献1886条经验 获得超2个赞
下面的代码总是正确的,因此是一个无限循环。
while (found != true && initial <= end)
middle = Math.round(initial + end) / 2;
将代码放在大括号内
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;
}
return position;i
}
添加回答
举报
0/150
提交
取消