Skip to content

Instantly share code, notes, and snippets.

@gubser
Created December 14, 2022 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gubser/49a5c8a60d655cd817e7c4ca993105b8 to your computer and use it in GitHub Desktop.
Save gubser/49a5c8a60d655cd817e7c4ca993105b8 to your computer and use it in GitHub Desktop.
Binary search with typings from https://stackoverflow.com/a/50612218
// 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