AlgoLab

O(n + k)·O(n + k) space·not stable
60599267494414214037

Starting counting sort on an array of 20 items.

Starting counting sort on an array of 20 items.
  1. 1count how many times each value from the smallest to the largest appears
  2. 2read the next value and increase its count by one
  3. 3once every value has been counted, walk through the possible values from smallest to largest
  4. 4while a value still has a remaining count, write it into the next position and reduce its count by one
  5. 5the array is fully sorted
Count updates
0
Writes
0
Accesses
0
Comparisons (stays 0 — counting sort never compares values)
0

Complexity

BestO(n + k)
AverageO(n + k)
WorstO(n + k)
Extra spaceO(n + k)
StableNo
n at n=20 predicts 20; this run took 0.

Counting sort

Counting sort counts how many times each distinct value appears in the array, then walks through the possible values from smallest to largest, writing each one back into the array as many times as it was counted. It never compares two values against each other, only against a stored count.

When it is the right choice

Counting sort is an excellent choice when the values are integers drawn from a range k that is small relative to n, such as exam scores out of 100 or ages in years — its O(n + k) time beats any comparison sort's O(n log n) once k is small enough. It is a poor choice when the range k is large or unbounded, since its extra space and time both scale with k as well as n; sorting a million distinct sixteen-digit account numbers this way would need a count array with quadrillions of cells.

How it works

Worth noticing

Cost

Best
O(n + k)
Average
O(n + k)
Worst
O(n + k)
Extra space
O(n + k)
Stable
No

Worth comparing

All algorithms