Created
February 9, 2022 00:01
-
-
Save kane-thornwyrd/e94a0b68c720048e0d9989d7d1b9370d to your computer and use it in GitHub Desktop.
I wrote this, as a refresher, better keep it just in case…
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
// The output should be the "difference" between each inputs, thus 0 mean identical. | |
type ComparatorFunction = <Type>(lookup: Type, pointer: Type ) => number | |
function bsearch<Type>( | |
dictionary: Array<Type>, | |
lookup: Type, | |
comparator: ComparatorFunction, | |
startIndex: number = 0, | |
endIndex: number = dictionary.length-1, | |
): Array<Type> { | |
if (startIndex>endIndex) return []; | |
const pivot = Math.floor((startIndex+endIndex)/2) | |
const comparison = comparator(lookup, dictionary[pivot]) | |
if( comparison === 0 ) return [dictionary[pivot]]; | |
return comparison > 0 ? | |
bsearch(dictionary, lookup, comparator, startIndex, pivot-1) | |
: bsearch(dictionary, lookup,comparator, pivot+1, endIndex) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment