Skip to content

Instantly share code, notes, and snippets.

@dukuo
Last active April 10, 2020 07:02
Show Gist options
  • Save dukuo/3bb4133172b33abee0a5c2fd1dcf49e7 to your computer and use it in GitHub Desktop.
Save dukuo/3bb4133172b33abee0a5c2fd1dcf49e7 to your computer and use it in GitHub Desktop.
Binary Search - Javascript
const binarySearch = (arr, val) => {
let min = 0
let max = arr.length - 1
while(min <= max ) {
const mid = Math.floor((min+max)/2)
if(arr[mid] === val) {
return mid
} else if(arr[mid] < val) {
min = mid + 1
} else {
max = mid - 1
}
}
return -1
}
const genRandArr = (num) => Array.from({length: num}, () => Math.floor(Math.random() * 10))
const n = 1000
const arr = genRandArr(n)
const s = 12
console.log(binarySearch(arr, s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment