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

二分查找 #22

Open
ChenPt opened this issue Aug 9, 2018 · 0 comments
Open

二分查找 #22

ChenPt opened this issue Aug 9, 2018 · 0 comments

Comments

@ChenPt
Copy link
Owner

ChenPt commented Aug 9, 2018

二分查找法适用于已经排好序的数据结构

// 递归版本
function binary_search(arr, start, end, value) {
  if(start > end) {
    return -1
 }
  let mid = Math.floor((start + end) / 2)
  if(value > arr[mid]) {
    return binary_search(arr, mid+1, end, value)
  }
  if(value < arr[mid]) {
    return binary_search(arr, start, mid - 1, value)
  }
  return mid
}

// 利用函数柯里化,只需要传`arr`和`value`两个参数
function curry_binary_search(arr, value) {
  return binary_search.call(null, arr, 0, arr.length - 1, value)
}
// test
curry_binary_search([1,2,3,4,5,6,7,8,9,10,11], 1)  // 0 , 返回`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