active
unsorted
sorted
5
0
3
1
8
2
1
3
9
4
2
5
6
6
4
7
Counting Sort: count occurrences, compute prefix sums, then place elements in order.
Works in O(n + k) where k is the range of values. No comparisons needed.
start
1 / 52
SPD0.5×
click to pause · hover for controls · fullscreen for more

Counting Sort

Sort integers in O(n+k) — no comparisons, just counting

Visual by thisgirltech

BeginnerSorting

Counting Sort is a non-comparison sorting algorithm. Instead of comparing elements against each other, it counts how many times each value appears, then uses those counts to place every element directly into its correct position in the output array.

This makes it exceptionally fast when the range of values (k) is small relative to the number of elements (n). There are no swaps, no comparisons — just counting and placing.

No comparisons

Never compares two elements — it counts occurrences. This breaks the O(n log n) lower bound for comparison sorts.

O(n + k) time

Linear in the number of elements plus the value range. Faster than any comparison sort when k is small.

Integer values only

Requires values to be non-negative integers within a known range — not suitable for floats or arbitrary objects.

TIP

Counting Sort shines when sorting integers in a small range — e.g. ages, grades, or frequencies. For large ranges or floating point values, use a comparison sort instead.

COLOUR LEGEND

Counting
Placing
Sorted
Scanned