Skip to content

Instantly share code, notes, and snippets.

@kdnk
Created November 29, 2016 08:37
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 kdnk/fd8bb65ffc6bd42044c1990a7805bc0d to your computer and use it in GitHub Desktop.
Save kdnk/fd8bb65ffc6bd42044c1990a7805bc0d to your computer and use it in GitHub Desktop.
main()
function main () {
let a = [5, 7, 15, 28, 29, 31, 39, 58, 68, 70, 95]
const key = 39
const index = binarySearch(a, a.length - 1, key)
console.log('index ', index)
}
function binarySearch (a, n, key) {
let pl = 0
let pr = n - 1
while (pl <= pr) {
let pc = Math.round((pl + pr) / 2)
if (a[pc] === key) {
return pc
} else if (a[pc] < key) {
pl = pc + 1
} else {
pr = pc - 1
}
}
return -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment