为什么这个二叉搜索找不到我的价值?



大家好,我的二进制搜索一直返回"未找到",因为它找不到我传递它的值。 请让我知道我做错了什么,谢谢!

const binary_search = (arr, value) => {
let high = arr.length -1;
let low = 0;
let mid = 0;
while (low <= high){
mid = Math.floor = ((high + low) / 2)
//middle value being searched
if (arr[mid] == value){
//return value
return arr[mid];
} else if (value > arr[mid]){
// move the low up one
low = mid + 1;
}   else  {
// move the high down one
high = mid -1;
}
}
return 'not found'
}

let array = [12, 45, 37, 37, 84, 61, 12, 266]

let sorted = array.sort (function(a,b){return a-b})
let wif = binary_search(sorted,37)
console.log(sorted)
console.log(wif)
const binary_search = (arr, value) => {
let high = arr.length -1;
let low = 0;
let mid = 0;
while (low <= high){
mid = Math.floor = ((high + low) / 2)
mid = Math.round(mid);
//middle value being searched
if (arr[mid] == value){
//return value
return arr[mid];
} else if (value > arr[mid]){
// move the low up one
low = mid + 1;
}   else  {
// move the high down one
high = mid -1;
}
}
return 'not found'
}

let array = [12, 45, 37, 37, 84, 61, 12, 266]

let sorted = array.sort (function(a,b){return a-b})
let wif = binary_search(sorted,37)
console.log(sorted)
console.log(wif)

mid 中的值 = Math.floor = ((高 + 低(/2( 在每次迭代中都处于中间状态,因此它无法获取索引。像 7/2 = 3.5 和 arr[3.5]。不会有任何价值。

你的代码说:

mid = Math.floor = ((high + low) / 2)

我不认为这就是你的意思

最新更新