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

binary_search #9

Open
Jenna-u opened this issue Aug 1, 2018 · 0 comments
Open

binary_search #9

Jenna-u opened this issue Aug 1, 2018 · 0 comments

Comments

@Jenna-u
Copy link
Owner

Jenna-u commented Aug 1, 2018

/**
* JavaScript实现二分查找
* @params list
* @params item
* return -1
*/

function binary_search(list, item) {
  // 设置最大数和最小数
  let low = 0
  let high = list[list.length - 1]
  let guess = 0 // 猜几次
  let mid = 0  // 初始化中间数

  while (low <= high) {  // 只要符合条件
    mid = parseInt((low + high) / 2, 10) // 就设置mid从数组的中间元素开始
    guess = list[mid]  
    if (guess === item) {  // 假设所猜的元素恰巧是数组中间那个数
      return mid  // 就返回
    } else if (guess > item) { // 大于则设置high 为mid的下一位
      high = mid - 1
    } else { // 否则low为mid的前一位
      low = mid + 1
    }
  } 
  return -1 // 条件不允许则返回 -1
}
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