首页 > 编程学习 > [编程题] 二分查找

[编程题] 二分查找

发布时间:2022/9/12 22:14:06

递归

function binarySearch(arr: number[], target: number, left: number = 0, right: number = arr.length - 1): number {
    if (left > right) {
        return -1
    }
    const mid = Math.floor((left + right) / 2)
    if (arr[mid] === target) {
        return mid
    }
    if (arr[mid] < target) {
        return binarySearch(arr, target, mid + 1, right)
    }
    return binarySearch(arr, target, left, mid - 1)
}

const arr = [-1, 0, 1, 2, 3, 4, 5, 6, 11, 44, 56, 77]

console.log(binarySearch(arr, 44)) // 9
console.log(binarySearch(arr, 99)) // -1
Copyright © 2010-2022 mfbz.cn 版权所有 |关于我们| 联系方式|豫ICP备15888888号