Created
December 14, 2022 17:15
-
-
Save gubser/49a5c8a60d655cd817e7c4ca993105b8 to your computer and use it in GitHub Desktop.
Binary search with typings from https://stackoverflow.com/a/50612218
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
// from https://stackoverflow.com/a/50612218 | |
export function binarySearch<X>(xs: X[], x: X) { | |
let start = 0; | |
let end = xs.length - 1; | |
while (start <= end) { | |
let mid = Math.floor((start + end) / 2); | |
if (xs[mid] === x) { | |
return mid; | |
} | |
if (x < xs[mid]) { | |
end = mid - 1; | |
} else { | |
start = mid + 1; | |
} | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment