Objective
To find the k-th smallest of a list (for example the median) you do not need to sort it entirely. Quickselect uses the idea of quicksort, but only continues with the group where the answer is.
Instructions
- Read
k(starting at 1) and a line with integers (there are at leastk). - Define
select(items, k): the pivot is the first element; separatesmaller,equalandlargeras in quicksort. - If
kfits in the smaller ones, continue recursively with them; if it falls in the equal ones, the answer is the pivot; otherwise continue with the larger ones, subtracting the elements already discarded. - Show
Position k: x.
3
7 2 9 4 5
Position 3: 5
Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.
Start exercise