Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

二分搜索 #63

Open
wl05 opened this issue Sep 22, 2019 · 0 comments
Open

二分搜索 #63

wl05 opened this issue Sep 22, 2019 · 0 comments

Comments

@wl05
Copy link
Owner

wl05 commented Sep 22, 2019

二分搜索:

  1. 选择数组的中间值。
  2. 如果选中值是待搜索值,那么算法执行完毕(值找到了)。
  3. 如果待搜索值比选中值要小,则返回步骤 1 并在选中值左边的子数组中寻找(较小)。
  4. 如果待搜索值比选中值要大,则返回步骤 1 并在选中值右边的子数组中寻找(较大)。

代码实现如下:

function binarySearch(arr, value) {
    let low = 0
    let high = arr.length - 1
    while (low <= high) {
        const midIndex = Math.floor((low + high) / 2)
        const mid = arr[midIndex]
        if (mid < value) { // 说明在mid的左边
            low = midIndex + 1
        } else if (mid > value) { // 说明在mid的右边
            high = midIndex - 1
        } else if (mid === value) { // 找到了
            return midIndex
        }
    }
    return -1
}

const arr = [1, 2, 3, 4, 5, 6, 7]
console.log(binarySearch(arr, 7))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant