Skip to content

Instantly share code, notes, and snippets.

@inodaf
Last active April 11, 2021 16:24
Show Gist options
  • Save inodaf/734092557fe7437bb5720d0af72dff0e to your computer and use it in GitHub Desktop.
Save inodaf/734092557fe7437bb5720d0af72dff0e to your computer and use it in GitHub Desktop.
// O(logn)
const binarySearch = (list: number[], item) => {
let [from, to] = [0, list.length - 1];
if (!item) return
while (from <= to) {
const index = Math.ceil((from + to) / 2);
const guess = list[index];
if (guess === item) return index;
if (guess > item) to = index - 1;
else from = index + 2;
}
return null;
}
const seed = Array(10).fill().map((item, index) => index + 1)
binarySearch(seed, 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment