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

破算法 #2

Open
fengT-T opened this issue Jan 28, 2018 · 0 comments
Open

破算法 #2

fengT-T opened this issue Jan 28, 2018 · 0 comments

Comments

@fengT-T
Copy link

fengT-T commented Jan 28, 2018

简单的二分搜索

Blog

破事水

  const source = [10, 3, 35, 24, 10, 9, 23, 14, 15, 56]
   const target = 23
   source.sort((a, b) => a - b)
   console.log(`source: ${source}`)
   console.log(`target: ${target}`)
   
   /**
    * 破二分搜索
    * @param {Array[int]} array 源数组
    * @param {int} low 搜索下界
    * @param {int} high 搜索上界
    * @param {int} target 搜索目标
    */
   function BinarySearch (array, low, high, target) {
     if (low > high) {
       return false
     }
     let mid = Math.floor((high + low) / 2)
     if (array[mid] > target) {
       return BinarySearch(array, low, mid - 1, target)
     } else if (array[mid] < target) {
       return BinarySearch(array, mid + 1, high, target)
     } else {
       return mid
     }
   }
   
   console.log(`result: ${BinarySearch(source, 0, source.length, target) + 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