Last active
December 6, 2022 14:49
-
-
Save ColinTimBarndt/9a599b0b186418064887a9b94e8fe668 to your computer and use it in GitHub Desktop.
Binary Search in Typescript
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>(arr: T[], entry: T, compare: (l: T, r: T) => number): number { | |
let mid: number = 0, | |
l: number = 0, | |
r: number = arr.length - 1, | |
e: T; | |
while (l <= r) { | |
mid = Math.floor((l + r) / 2); | |
if ((e = arr[mid]!) === entry) | |
return mid; | |
compare(entry, e) < 0 | |
? r = mid - 1 | |
: l = mid + 1; | |
} | |
return -l-1; | |
} |
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
const binarySearch = (arr: (number | string)[], entry: (number | string)): number => { | |
let mid: number = 0, | |
l: number = 0, | |
r: number = arr.length - 1, | |
e: string | number; | |
while (l <= r) { | |
mid = Math.floor((l + r) / 2); | |
if ((e = arr[mid]!) === entry) | |
return mid; | |
e > entry | |
? r = mid - 1 | |
: l = mid + 1; | |
} | |
return -l-1; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment