Skip to content

Instantly share code, notes, and snippets.

@foxymiles
Created March 4, 2022 13:39
Show Gist options
  • Save foxymiles/168d55286236579e3adb492cfd360f8b to your computer and use it in GitHub Desktop.
Save foxymiles/168d55286236579e3adb492cfd360f8b to your computer and use it in GitHub Desktop.
Binary Search in TS
function binarySearch<T>(values: T[], compare: (v: T) => number): number {
let left = 0;
let right = values.length - 1;
let ans = -1;
while (left <= right) {
const mid = Math.floor(left + (right - left) / 2);
const comp = compare(values[mid]!);
if (comp === 0) {
return mid;
}
if (comp < 0) {
left = mid + 1;
ans = mid + 1;
} else {
ans = mid;
right = mid - 1;
}
}
return ans;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment