js查找数组下标算法 二分查找法 查找数字所在下标

// 二分查找法 查数字所在下标
function search(list, item) {
    let low = 0
    let high = list.length - 1
    while (low <= high) {
        mid = (low + high) / 2
        mid = Math.ceil(mid); //向上取整
        guess = list[mid]
        if (guess == item) {
            return mid
        } else if (guess > item) {
            high = mid - 1
        } else {
            low = mid + 1
        }
    }
}
const arr = [1, 3, 5, 7, 8, 9, 12, 13]
console.log(search(arr, 9)) // 5

运行速度快与普通查找法。

posted @ 2021-05-14 23:35  herry菌  阅读(234)  评论(0编辑  收藏  举报