二分查找

function binarySearch(arr, value) {
    let minIndex = 0
    let maxIndex = arr.length - 1
    let middleValue

    while (minIndex <= maxIndex) {
        let middleIndex = Math.floor((minIndex + maxIndex) / 2)
        middleValue = arr[middleIndex]
        if (value < middleValue) {
            maxIndex = middleIndex - 1
        } else if (value > middleValue) {
            minIndex = middleIndex + 1
        } else {
            return middleIndex
        }
    }

    return -1
}

你可能感兴趣的:(算法)