乐趣区

关于算法:二分查找

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
}
退出移动版