Counting sort

Sorting by counting · Part of Search and sort

Key idea

Practice

6 questions · about 3 min

Explained step by step

Counting sort

Counting sort sorts without comparing, by counting. For an array of non-negative integers, it first finds the maximum m and creates an array of m + 1 counters, all at 0. Then it walks the data and, for each number, adds 1 to its counter: the counter at index 5 says how many 5s there are. Since the indexes are already in order, at the end the counters are walked and each number is written as many times as its counter says.

The simple version writes numbers, but it's no good for sorting objects, like products by price: the rest of each one's data would be lost. For that, prefix sums are used: prefix[i] is the sum of the counters from 0 to i, and says the last element with value i goes at position prefix[i] − 1. The original array is walked from back to front, each element is placed at its position and its prefix sum drops by 1.

Counting sort walks the n data items and the m + 1 counters: O(n + m) in time. If there's lots of data and a small range, n much bigger than m, it's practically O(n), faster than any comparison sort. It uses O(n + m) memory: the counters array and the result array. It isn't adaptive.

Counting sort has strict requirements. It works directly only with non-negative integers; other data has to be converted without losing order, for example adding a constant to negatives. And it's only worth it when the range is small: if values go up to 1 billion, the counters array takes 1 billion slots, and if there's little data, walking it costs more than sorting by comparison.

Counting sort is used when there's lots of data with few possible values: grades, ages, hours of the day, letters, 1-to-5-star ratings. It's also the key piece of radix sort, which applies it digit by digit to sort numbers with more possible values.

Stable sort

Counting sort with prefix sums is stable if the original array is walked from back to front. Since each value is filled right to left in the result, the last to appear goes in its group's last spot, so equal values keep their order. Walking front to back would leave equal values reversed.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Sorting by counting