Last active
April 11, 2021 16:24
-
-
Save inodaf/734092557fe7437bb5720d0af72dff0e 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
// 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