js二分查找伪代码

为什么使用二分查找?时间复杂度低,为O(log n)

思想:每次缩短一半来快速限定目标所在区间

代码:

const list = [1, 3, 2].sort((a, b) => a - b)
    let left = 0, right = list.length - 1
    while (left <= right) {
        const center = Math.floor((left + right) * 0.5)
        if (list[center] === target) {
            return true
        } else if (list[center] < target) {
            left = center + 1
        } else {
            right = center - 1
        }
    }
    return false

猜你喜欢

转载自blog.csdn.net/qq_43119912/article/details/125783643
今日推荐