Created
November 29, 2016 08:37
-
-
Save kdnk/fd8bb65ffc6bd42044c1990a7805bc0d to your computer and use it in GitHub Desktop.
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
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