Algorithms · Visualized
Counting Sort
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
Counting Sort doesn't compare elements at all. Time: O(n + k) average, O(n + k), where k is the range of input values worst; space: O(n + k) — needs a count array and an output array.
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Counting Sort
SortingCounting Sort doesn't compare elements at all. It counts how many times each distinct value appears, then uses those counts to figure out exactly where each value belongs in the final sorted array. It only works well when the values are integers within a known, reasonably small range.
How Counting Sort Works
- Find the range of the input values (minimum and maximum).
- Create a count array covering that range, initialised to zero.
- Go through the input and increment the count for each value seen.
- Convert the counts into a running total (prefix sum), so each entry tells you the position where that value's block ends.
- Walk the input array (often from the end, to keep the sort stable) and place each element into its correct position in the output array using the prefix-sum counts, decrementing as you go.
Counting Sort Worked Example
Input: [4, 2, 2, 8, 3, 3, 1]
Counts for values 1-8: {1:1, 2:2, 3:2, 4:1, 8:1}. Prefix sums tell us 1 occupies position 0, 2 occupies positions 1-2, 3 occupies 3-4, 4 occupies 5, 8 occupies 6. Placing each input element into its slot gives the sorted array: [1,2,2,3,3,4,8].
def counting_sort(a):
k = max(a) if a else 0
cnt = [0] * (k + 1)
out = [0] * len(a)
for v in a:
cnt[v] += 1
for i in range(1, k + 1):
cnt[i] += cnt[i - 1]
for v in reversed(a):
cnt[v] -= 1
out[cnt[v]] = v
return outBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Counting Sort Time & Space Complexity
When to Use Counting Sort
- Sorting integers with a small, known range — e.g. exam scores from 0-100, ages, grades.
- As a subroutine inside Radix Sort, which sorts digit-by-digit using counting sort.
- Situations needing a stable, linear-time sort where the value range isn't huge.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.