SOURCE

function binarySearch(sortedArray, seekElement) {
    // 1. 设置初始的左右index
    let startIndex = 0
    let endIndex = sortedArray.length - 1

    // 2. 二分遍历直到左超过右
    while (startIndex <= endIndex) {
        // 4. 获取中间index(左+差值的一半)
        const middleIndex = startIndex + Math.floor((endIndex - startIndex) / 2)

        // 5. 找不到就二分,找到返回下标
        if (sortedArray[middleIndex] < seekElement) {
            startIndex = middleIndex + 1
        } else if (sortedArray[middleIndex] > seekElement) {
            endIndex = middleIndex - 1
        } else {
            return middleIndex
        }
    }

    // 找不到返回-1
    return -1
}

const arr = [1, 2, 3, 4, 4, 6, 6, 41, 53, 87]
const res = binarySearch(arr, 41)

console.log(res)
console 命令行工具 X clear

                    
>
console