Last active
December 22, 2018 19:47
-
-
Save dhassanali/433f5eb43027166863bc2e757c3c01af to your computer and use it in GitHub Desktop.
Simple Binary Search in JS
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
function binarySearch(elm, set) { | |
let i = 0 | |
let j = set.length - 1 | |
while (i < j) { | |
const m = Math.floor((j + i) / 2); | |
if (elm > set[m]) | |
i = m + 1 | |
else | |
j = m | |
} | |
if (elm == set[i]) | |
return i | |
return -1 | |
} | |
// const set = [3, 4, 5, 6, 7, 8, 9, 10] | |
// console.log(binary(9, set)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment