algorithm: init, add binSearch
This commit is contained in:
25
algorithm.ts
Normal file
25
algorithm.ts
Normal 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];
|
||||
}
|
||||
Reference in New Issue
Block a user