Created
July 12, 2020 07:30
-
-
Save KR1470R/5e7d0ca71c53f83233032d5d3bbfe725 to your computer and use it in GitHub Desktop.
Binary search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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