Counting Sort visualization

Count occurrences of each value, then rebuild the array from the counts.

No comparisons at all: for small integer ranges, tally how many times each value appears, then write each value out count times.

Negative numbers are handled by offsetting: value v is counted in slot v − min, so the count array spans exactly min..max.

Runs in O(n + k) where k = max − min + 1 — fantastic for ages, grades or digits, wasteful when k is huge.

Complexity

Time: best O(n + k), average O(n + k), worst O(n + k). Space: O(k). Difficulty: Intermediate.

Pseudocode

procedure countingSort(A):
  lo ← min(A); C ← zeros of size max(A) − lo + 1
  for x in A: C[x − lo] ← C[x − lo] + 1
  k ← 0
  for v ← lo to max(A):
    repeat C[v − lo] times: A[k] ← v; k ← k + 1

More sorting algorithms