Skip to content

Instantly share code, notes, and snippets.

@KR1470R
Created July 12, 2020 07:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KR1470R/5e7d0ca71c53f83233032d5d3bbfe725 to your computer and use it in GitHub Desktop.
Save KR1470R/5e7d0ca71c53f83233032d5d3bbfe725 to your computer and use it in GitHub Desktop.
Binary search
let arr = [3,4,15,17,20,23,24,31,33,37,40,51,54]
function binary_search(a,e){
let high = a.length-1
let mid = 0
let low = 0
while (low <= high) {
mid = Math.floor((low+high)/2)
if (a[mid] === e){
return arr[mid]
}else if (a[mid] < e){
low = mid+1
}else{
high = mid-1
}
}
return undefined
}
let sortedArr = arr.sort((a,b)=>{a-b})
console.log(sortedArr)
let res = binary_search(sortedArr,33)
console.log(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment