Skip to content

Quickselect ​

Selects the value at zero-based position k in the sorted order without sorting the complete array. The input is an i32[]; the result is i32? and is absent when k is outside the array.

tyrus
import { quickselect } from "tyrus:algorithm";

const value: i32? = quickselect([7, 1, 4, 9, 2], 2);
print(value ?? -1); // 4

Study result ​

quickselectInfo returns a SelectionInfo with the original input snapshot and deterministic partition, comparison, and swap metrics.

tyrus
interface SelectionInfo {
    values: i32[];
    selected: i32?;
    rank: usize;
    comparisonCount: usize;
    swapCount: usize;
    partitionCount: usize;
}
tyrus
import { SelectionInfo, quickselectInfo } from "tyrus:algorithm";

const info: SelectionInfo = quickselectInfo([7, 1, 4, 9, 2], 2);
print(info.values); // [7, 1, 4, 9, 2]
print(info.selected ?? -1); // 4
print(info.rank); // 2
print(info.comparisonCount); // 10
print(info.swapCount); // 3
print(info.partitionCount); // 1

The average complexity is O(n), with O(n²) worst-case complexity and O(1) auxiliary space.