SOURCE

const nums = [2, 3, 5, 7, 9, 9, 11, 18, 1018]

/**
 * 闭区间
 */
const binarySearch = function (nums, target) {
    if (nums.length === 0) {
        return -1
    }
    // 闭区间[low,high]
    let low = 0, high = nums.length - 1, mid
    // 重点:因为是闭区间,所以low=high时,还有一个值要判断
    while (low <= high) {
        mid = Math.floor(low + (high - low) / 2)
        if (nums[mid] === target) {
            return mid
        } else if (nums[mid] < target) {
            // 因为是闭区间,搜索范围变为[mid+1,high]
            low = mid + 1
        } else {
            // 因为是闭区间,搜索范围变为[low,mid-1]
            high = mid - 1
        }
    }
    return -1
}

console.log("result", binarySearch(nums, 9))

/**
 * 开区间
 */
const binarySearch1 = function (nums, target) {
    if (nums.length === 0) {
        return -1
    }
    // 相当于搜索一个前闭后开的区间[low,high)
    let low = 0, high = nums.length, mid
    //重点:因为是前闭后开,所以low=high时,已经没有值了
    while (low < high) {
        mid = Math.floor(low + (high - low) >>>1)
        if (nums[mid] === target) {
            return mid
        } else if (nums[mid] < target) {
            // 因为是前闭后开,搜索范围变为[mid+1,high)
            low = mid + 1
        } else {
            // 因为是前闭后开,搜索范围变为[low,mid)
            high = mid
        }
    }
    return -1
}

console.log("result", binarySearch1(nums, 9))
console 命令行工具 X clear

                    
>
console