js 二分查找

108 阅读1分钟

题目:用js手写二分查找【给定一个有序数组,给出一个数,找出这个数在这个数组的下标】

理念:分而治之(缩小一半,直到找到目标值)

示例:

const arr = [1, 6, 9, 10, 40]

const findElement = 10
function BinarySearch (arr, element) {
    let minIndex = 0
    let maxIndex = arr.length - 1
    
    let testElement
    
    while(minIndex <= maxIndex) {
        let middleIndex = Math.floor((minIndex + maxIndex) / 2)
        testElement = arr[middleIndex]
        
        if (testElement < element) {
            maxIndex = middleIndex + 1
        } else if (testElement > element) {
            minIndex = middleIndex - 1
        } else {
            return middleIndex
        }
    }
    
    return -1
}