Last active
July 7, 2020 13:20
-
-
Save karol-majewski/b6e221c434f97ea05ccd7b804e6a7995 to your computer and use it in GitHub Desktop.
Easy binary search in TypeScript
This file contains hidden or 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
type Comparator<T> = (x: T, y: T) => Comparison; | |
enum Comparison { | |
LessThan = -1, | |
Equal = 0, | |
GreaterThan = 1, | |
} | |
function search<T>(array: T[], item: T, compare: Comparator<T>): number { | |
let [left, right] = [0, array.length - 1]; | |
while (left <= right) { | |
let middle = Math.floor((left + right) / 2); | |
switch (compare(array[middle], item)) { | |
case Comparison.Equal: | |
return middle; | |
case Comparison.LessThan: | |
left = middle + 1; | |
break; | |
case Comparison.GreaterThan: | |
right = middle - 1; | |
break; | |
} | |
} | |
return -1; | |
} | |
const comparator: Comparator<number> = (left, right) => { | |
if (left === right) { | |
return Comparison.Equal; | |
} else if (left < right) { | |
return Comparison.LessThan | |
} else { | |
return Comparison.GreaterThan | |
} | |
} | |
search([0, 1, 2, 3, 4], 2, comparator); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another solution: