日本語

NON-COMPARISON SORTS

Counting Sort, visualised

Counting sort counts how many times each value appears and writes the values back from smallest to largest using those counts. It never compares elements with each other.

Run Counting Sort in the visualizer →

Opens the Sorting Cinema visualizer with 16 elements in English.

How it works

  1. Find the maximum and prepare a count array for values 0 to the maximum.
  2. Read the array from the left and count each value.
  3. For each value from 1 to the maximum, write it back from the front as many times as counted (this app handles positive integers).

Complexity and stability

Best
O(n + k)
Average
O(n + k)
Worst
O(n + k)
Extra space
O(k)
Stability
— (values are rewritten from counts, so original element order is not tracked)

With k as the range of values, the rule of thumb is O(n + k) (as stated in the learning guide). The count array needs space for the value range. A very wide range makes it inefficient, so it is not always faster than comparison sorts.

Source of facts: Complexity follows the learning guide's comparison table and text, and this app's implementation.

Trace on a small array

The first operations on the input [3, 1, 4, 1, 2], following the same steps as the app.

#OperationArray after
1Count [0]=3[3, 1, 4, 1, 2]
2Count [1]=1[3, 1, 4, 1, 2]
3Count [2]=4[3, 1, 4, 1, 2]
4Count [3]=1[3, 1, 4, 1, 2]
5Count [4]=2[3, 1, 4, 1, 2]
6Write 1 to [0][1, 1, 4, 1, 2]
7Write 1 to [1][1, 1, 4, 1, 2]
8Write 2 to [2][1, 1, 2, 1, 2]

…and so on. In this trace, 10 compare / swap / write operations in total produce [1, 1, 2, 3, 4].

Suitable inputs and caveats

  • Suited to integer data with a narrow value range.
  • The visualisation has two phases: reading every element, then writing values back from smallest.
  • This app counts values and rewrites them, so it does not represent the original order of equal elements.

FAQ

Why doesn't counting sort compare elements?

It uses each value as an index into the count array and rebuilds the order from the counts, so no element-to-element comparison is needed.

What if the value range is very wide?

The count array must cover the whole range, so k in O(n + k) becomes large. A comparison sort or radix sort may suit better.