Classic algorithms · 20 / 22 Exercise Hard

The k-th smallest

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 least k).
  • Define select(items, k): the pivot is the first element; separate smaller, equal and larger as in quicksort.
  • If k fits 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.
Input
3
7 2 9 4 5
Output
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