Created
September 1, 2021 12:58
-
-
Save dominictobias/001a40cd1da49ee57d4d4c6a4d7135a9 to your computer and use it in GitHub Desktop.
Binary Search (JS/TS)
This file contains hidden or 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<T = any>( | |
findValue: number, | |
items: T[], | |
getValue: (item: T) => number | |
) { | |
let lo = 0 | |
let hi = items.length - 1 | |
while (lo <= hi) { | |
const mi = (lo + hi) >>> 1 | |
const value = getValue(items[mi]) | |
if (findValue < value) { | |
hi = mi - 1 | |
} else if (findValue > value) { | |
lo = mi + 1 | |
} else { | |
return mi | |
} | |
} | |
return lo > 0 ? lo - 1 : 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reversed version: