Skip to content
StackDecode
SortingAnimated

Counting Sort

Count occurrences of each small integer, then rebuild the list.

Time

O(n + k)

Extra space

O(k)

Use it for

Integers in a small known range.

How it works

  1. No comparisons at all. Works for small whole numbers.
  2. Count how many times each value appears.
  3. Turn the counts into running totals: the total for value v tells how many items are ≤ v, i.e. where the last v goes.
  4. Walk the input backwards, put each item at its position and decrement the total. Walking backwards keeps equal items in order (stable).

Watch it run

Loading animation…