diff --git a/algorithm.ts b/algorithm.ts new file mode 100644 index 0000000..9e89b8a --- /dev/null +++ b/algorithm.ts @@ -0,0 +1,25 @@ +/** + * Performs a binary search within a specified range. + * @param begin The starting index of the search range. + * @param end The ending index of the search range. + * @param beforeHalf A list of predicates indicating conditions before the midpoint. + * @returns A tuple containing the indices representing the binary search state: [begin, half, end]. + */ +export function binSearch(begin: number, end: number, beforeHalf: boolean[]): [number, number, number] { + const gHalf = () => { return Math.floor((end - begin) / 2) + begin; } + + for (const pred of beforeHalf) { + const half = gHalf(); + if (pred) { + // Happens before "half" + end = half; + } else { + begin = half; + } + } + + const half = gHalf(); + console.log(`Checking range: [${begin}, ${end}], ${end - begin} objects, mid ${half}`); + + return [begin, half, end]; +}