为什么这个二进制搜索找不到我的值?

问题描述 投票:0回答:2

大家好,我的二进制搜索始终返回“未找到”,因为它找不到通过它的值。请让我知道我在做什么错,谢谢!

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)
javascript binary-search
2个回答
0
投票
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 =((high + low)/ 2)在每次迭代中都处于整数状态,因此无法获取索引。例如7/2 = 3.5和arr [3.5]。没有价值。


-1
投票

您的代码说:

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

我认为那不是你的意思

© www.soinside.com 2019 - 2024. All rights reserved.