Created
March 4, 2022 13:39
-
-
Save foxymiles/168d55286236579e3adb492cfd360f8b to your computer and use it in GitHub Desktop.
Binary Search in TS
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
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