Skip to content

Instantly share code, notes, and snippets.

@kane-thornwyrd
Created February 9, 2022 00:01
Show Gist options
  • Save kane-thornwyrd/e94a0b68c720048e0d9989d7d1b9370d to your computer and use it in GitHub Desktop.
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…
// 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