algorithm: init, add binSearch

This commit is contained in:
2024-06-16 02:32:32 +08:00
parent dd67719b4e
commit d0716f59ac

25
algorithm.ts Normal file
View File

@@ -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];
}