Classic algorithms · 19 / 22 Exercise Medium

Counting sort

Objective

When the values are small integers, there is no need to compare: you count how many times each value appears and rebuild the sorted list. Its cost is linear, O(n + k).

Instructions

  • Read a line with integers between 0 and 20.
  • Create a list of 21 counters and add 1 at the position of each number read.
  • Show Counts: ... with the values that appear, from smallest to largest, with the format value:times separated by spaces.
  • Show Sorted: ... with the numbers sorted, rebuilt from the counters (without using sorted).
Input
3 1 3 0 1 3
Output
Counts: 0:1 1:2 3:3
Sorted: 0 1 1 3 3 3

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise