1. Count occurrences
Create C[0…30], initially filled with zeros. After reading the students, the only nonzero cells are C[18]=2, C[24]=2, C[27]=1 and C[30]=1.
Sorting algorithms · 5/7
Replaces comparisons with counts of integer keys.
Count how often each value occurs. After cumulative sums, C[v] tells how many elements are ≤ v, so the next occurrence of v belongs at C[v]−1. Scanning the input from right to left and decreasing the counter produces stable output.
Suppose we want to sort the students in a course using their grade as the key, which can only be an integer from 0 to 30. The range contains just 31 possible values: instead of comparing students in pairs, Counting sort can reserve one counter for each grade.
Create C[0…30], initially filled with zeros. After reading the students, the only nonzero cells are C[18]=2, C[24]=2, C[27]=1 and C[30]=1.
Add each cell to the previous one. Now C[18]=2, C[24]=4, C[27]=5 and C[30]=6: for example, four students have a grade ≤24, and the last position reserved for a 24 is C[24]−1=3.
Scan the list from right to left. Each student with grade v goes into B[C[v]−1], then C[v] is decreased. The result is: Luca 18, Marco 18, Anna 24, Paolo 24, Sara 27, Giulia 30.
Each bar represents one element. Colors identify compared elements, the pivot or key, the final region and the active range.
Use 2 to 16 values from 0 to 999, spanning a range no wider than 80.
C[0 … k] ← 0for value in A: C[value]++for i ← 1 to k: C[i] ← C[i] + C[i − 1]for i ← n − 1 downto 0 B[C[A[i]] − 1] ← A[i] C[A[i]]--copy B into AThe highlighted line corresponds to the operation described by the visualizer. Index-management details are intentionally simplified.
Reading n items and initializing k counters is necessary: Θ(n+k).
Input order does not change the passes: Θ(n+k).
Worst case performs the same linear passes.
Θ(k) counters and Θ(n) stable output: Θ(n+k), not in place.
Stability concerns the relative order of elements with equal keys.
This classification refers to the version shown on this page.
Excellent for integers whose range k is not much larger than n.
A huge max−min range wastes time and memory. This visualizer accepts nonnegative integers.