Skip to content

Instantly share code, notes, and snippets.

@dhassanali
Last active December 22, 2018 19:47
Show Gist options
  • Save dhassanali/433f5eb43027166863bc2e757c3c01af to your computer and use it in GitHub Desktop.
Save dhassanali/433f5eb43027166863bc2e757c3c01af to your computer and use it in GitHub Desktop.
Simple Binary Search in JS
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