RosettaCodeData/Task/Quickselect-algorithm/Mathematica/quickselect-algorithm.math

31 lines
818 B
Plaintext

Quickselect[ds : DataStructure["DynamicArray", _], k_] := QuickselectWorker[ds, 1, ds["Length"], k];
QuickselectWorker[ds_, low0_, high0_, k_] := Module[{pivotIdx, low = low0, high = high0},
While[True,
If[low === high,
Return[ds["Part", low]]
];
pivotIdx = SelectPartition[ds, low, high];
Which[k === pivotIdx,
Return[ds["Part", k]],
k < pivotIdx,
high = pivotIdx - 1,
True,
low = pivotIdx + 1
]
]
];
SelectPartition[ds_, low_, high_] := Module[{pivot = ds["Part", high], i = low, j},
Do[
If[ds["Part", j] <= pivot,
ds["SwapPart", i, j];
i = i + 1
]
,
{j, low, high - 1}
];
ds["SwapPart", i, high];
i
];
ds = CreateDataStructure["DynamicArray", {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}];
Quickselect[ds, #] & /@ Range[10]