Binary Search
Searches an ascending i32[] and returns the zero-based index as usize?. The result is absent when the value does not occur. The array must already be sorted in ascending order.
tyrus
import { binarySearch } from "tyrus:algorithm";
const index: usize? = binarySearch([1, 2, 4, 7, 9], 7);
print(index ?? 99); // 3Study result
binarySearchInfo returns a SearchInfo with an independent input snapshot and deterministic comparisons and probes.
tyrus
interface SearchInfo {
values: i32[];
target: i32;
index: usize?;
comparisonCount: usize;
probeCount: usize;
}tyrus
import { SearchInfo, binarySearchInfo } from "tyrus:algorithm";
const info: SearchInfo = binarySearchInfo([1, 2, 4, 7, 9], 7);
print(info.values); // [1, 2, 4, 7, 9]
print(info.target); // 7
print(info.index ?? 99); // 3
print(info.comparisonCount); // 3
print(info.probeCount); // 3The search runs in O(log n) time and uses O(1) auxiliary space.
