Input Array
4
2
2
8
3
3
1
Frequency Counts (Indices 0-9)
0
0
0
1
0
2
0
3
0
4
0
5
0
6
0
7
0
8
0
9
Sorted Output

Counting Sort

If we know the range of our numbers (e.g., 0-9), we don't need to compare them. We can just count how many times each number appears.

Count 4

Found a 4. Increment the counter at index 4.

Count 2

Found a 2. Increment index 2.

Count 2 Again

Another 2! Increment index 2 to 2.

Count 8

Found an 8.

Count 3

Found a 3.

Count 3 Again

Another 3.

Count 1

Found a 1. Counting phase complete!

Reconstruct: Index 0

Index 0 has count 0. Nothing to add.

Reconstruct: Index 1

Index 1 has count 1. Add one '1' to the output.

Reconstruct: Index 2

Index 2 has count 2. Add a '2'.

Reconstruct: Index 2

Still have one '2' left. Add it.

Reconstruct: Index 3

Index 3 has count 2. Add '3'.

Reconstruct: Index 3

Add another '3'.

Reconstruct: Index 4

Index 4 has count 1. Add '4'.

Reconstruct: Indices 5,6,7

Counts are zero. Skip.

Reconstruct: Index 8

Index 8 has count 1. Add '8'.

Sorted!

We reconstructed the sorted array just by counting frequencies. No comparisons were made.

Blazing Fast

O(n + k). If the range (k) is small, this is faster than any comparison sort. If k is huge (e.g., 1 billion), this is terrible.

Count, Then Write.

Counting Sort is the simplest non-comparison sort, ideal for small ranges.

AlgoAnimator: Interactive Data Structures