Picture a teacher holding a stack of 200 quiz papers, every score somewhere between 0 and 10. You could shuffle the papers around one pair at a time. Or you could do something lazier and smarter: set out eleven trays labelled 0 to 10, drop each paper into its tray, then pick the trays up in order. Nobody ever compares one paper with another.
That tray trick is counting sort. It’s one of the few sorting algorithms that never compares two values, and that’s how it can run in O(n + k) time, which beats the O(n log n) ceiling every comparison sort has to live with. In this guide, we’ll walk through how the counting sort algorithm works, trace a full counting sort example by hand, write counting sort in Python, and untangle its time complexity and stability. If you’ve been following the series, this one is the odd one out next to bubble sort, selection sort, insertion sort, merge sort, quick sort and heap sort, and that’s exactly why it’s worth learning.
What Is Counting Sort?
Counting sort is a non-comparison sorting algorithm for whole numbers. Instead of asking “is this bigger than that?”, it counts how many times each value shows up, then uses those counts to work out where every value belongs in the sorted list. Harold H. Seward came up with it back in 1954.
There’s one big condition: it works best when the values fall in a small, known range, like ages, exam marks, star ratings or letters of the alphabet. The size of that range is the k in O(n + k), and we’ll come back to it more than once.
Wait, How Can It Beat O(n log n)?
Fair question. You’ve probably seen O(n log n) described as the speed limit for sorting. It is, but only for comparison sorts, the ones that figure out the order by comparing pairs of items. Merge sort, quick sort and heap sort all belong to that group.
Counting sort sidesteps the limit by using the values themselves as positions in an array. No comparisons, so the limit doesn’t apply. The price you pay is extra memory and that small-range requirement.
How Does Counting Sort Work?
Counting sort runs in four steps:
- Set up. Find the biggest value, then make a count array with one slot for every value from 0 up to that maximum, all starting at zero.
- Count. Walk through the input list and add 1 to the slot that matches each value.
- Add up. Turn the counts into running totals. Each slot now tells you how many values are less than or equal to its number, which also tells you where the last copy of that value should land.
- Place. Walk through the input list from right to left. For each value, look up its running total, drop the value into that position of a new output list, and subtract 1 from the slot.
Going right to left in the last step looks like a strange detail, but it’s what keeps equal values in their original order. We’ll see why in the stability section.
Counting Sort Step-by-Step Example
Let’s sort this list in ascending order:
[4, 2, 2, 5, 3, 3, 1]
You may have noticed this isn’t our usual [29, 10, 14, 37, 13] list. That one would need 38 count slots just to sort five numbers, which is a perfect preview of counting sort’s weak spot. This list has small values and a few repeats, which is where the algorithm shines.
Watch Counting Sort in Action
Follow three rows: the input list, the count array (one slot for each possible value), and the output list as it fills up.
Phase 1: count the values
The biggest value is 5, so we make six slots, for the values 0 to 5, and tally each number as we read it. After one pass the count array is [0, 1, 2, 2, 1, 1]. Read it like this: zero 0s, one 1, two 2s, two 3s, one 4 and one 5.
Phase 2: turn the counts into running totals
Now add each slot to the one before it: 0, then 0 + 1, then 1 + 2, then 3 + 2, then 5 + 1, then 6 + 1. That gives [0, 1, 3, 5, 6, 7]. Slot 3 reads 5, which means five values in the list are 3 or smaller, so the last 3 should sit in position 4 (counting from 0).
Phase 3: place the values from right to left
- Read
1(the last item). Slot 1 says 1, so it goes in position 0. Slot 1 drops to 0. Output: [1, _, _, _, _, _, _] - Read
3. Slot 3 says 5, so it goes in position 4. Slot 3 drops to 4. Output: [1, _, _, _, 3, _, _] - Read the other
3. Slot 3 now says 4, so it goes in position 3. Output: [1, _, _, 3, 3, _, _] - Read
5. Slot 5 says 7, so it goes in position 6. Output: [1, _, _, 3, 3, _, 5] - Read
2. Slot 2 says 3, so it goes in position 2. Output: [1, _, 2, 3, 3, _, 5] - Read the other
2. Slot 2 now says 2, so it goes in position 1. Output: [1, 2, 2, 3, 3, _, 5] - Read
4(the first item). Slot 4 says 6, so it goes in position 5. Output: [1, 2, 2, 3, 3, 4, 5]
Final answer: [1, 2, 2, 3, 3, 4, 5].
Counting Sort in Python
Here's a clean, stable version. It returns a new sorted list instead of changing the original one:
def counting_sort(arr):
if not arr:
return []
k = max(arr) # the biggest value sets the size of the count array
count = [0] * (k + 1)
# Step 1: tally how many times each value shows up
for value in arr:
count[value] += 1
# Step 2: turn the tallies into running totals
for i in range(1, k + 1):
count[i] += count[i - 1]
# Step 3: place values from right to left to keep the sort stable
output = [0] * len(arr)
for value in reversed(arr):
count[value] -= 1
output[count[value]] = value
return output
numbers = [4, 2, 2, 5, 3, 3, 1]
print(counting_sort(numbers))
# Output: [1, 2, 2, 3, 3, 4, 5]What each part does:
- The early
if not arrcheck handles an empty list, becausemax()would raise an error on one. [0] * (k + 1)makes one slot for every value from0tok. The+ 1matters, since counting starts at zero.- The first loop is the tally. The second loop builds the running totals.
- The last loop walks the input backwards with
reversed(arr). It subtracts 1 from the slot first, and that new number is exactly the output position for the value.
A shorter version for beginners
If you're only sorting plain integers, you can skip the running totals. Count the values, then rebuild the list straight from the counts:
def counting_sort_simple(arr):
if not arr:
return []
count = [0] * (max(arr) + 1)
for value in arr:
count[value] += 1
result = []
for value, times in enumerate(count):
result.extend([value] * times)
return result
print(counting_sort_simple([4, 2, 2, 5, 3, 3, 1]))
# Output: [1, 2, 2, 3, 3, 4, 5]This one is easier to read, but it rebuilds the values from scratch, so it can't carry extra data along with them, like a name attached to each score. For that you need the stable version above.
Counting sort with negative numbers
An array can't have a slot at position -1, so the trick is to shift every value by the smallest one in the list. The smallest value lands in slot 0, and everything else lines up behind it:
def counting_sort_with_negatives(arr):
if not arr:
return []
low, high = min(arr), max(arr)
count = [0] * (high - low + 1)
for value in arr:
count[value - low] += 1
for i in range(1, len(count)):
count[i] += count[i - 1]
output = [0] * len(arr)
for value in reversed(arr):
count[value - low] -= 1
output[count[value - low]] = value
return output
print(counting_sort_with_negatives([3, -1, 2, -1, 0]))
# Output: [-1, -1, 0, 2, 3]Here's a sneaky Python quirk worth knowing. If you feed a negative number to the plain version, Python won't always complain. An index of -1 quietly points at the last slot, so your counts get corrupted without a single error message. Shifting by the minimum avoids that whole mess.
Counting Sort Time and Space Complexity
| Case | Time complexity |
|---|---|
| Best | O(n + k) |
| Average | O(n + k) |
| Worst | O(n + k) |
| Extra space | O(n + k) |
Here n is how many items you're sorting, and k is the size of the range of values. For a list whose values run from 0 to 5, that's 6 slots. If Big O still feels fuzzy, our Big O notation for beginners guide covers the basics.
Where does O(n + k) come from?
- The counting pass touches each of the
nitems once, so it costsO(n). - The running totals walk the count array once, so they cost
O(k). - The placement pass touches each item once more, which is another
O(n).
Add those up and you get roughly 2n + k steps, which Big O simplifies to O(n + k). Space is O(n + k) too: a count array with k slots plus an output list with n items. Notice there's no real best or worst case here. Counting sort does the same amount of work however the list starts out.
When k gets out of hand
If k is about the same size as n (or smaller), counting sort is effectively linear, and that's great. But if k is far bigger than n, it falls apart. Sorting [3, 7, 1000000] would build a count array with a million and one slots just to sort three numbers. Merge sort wouldn't care how big the values were.
Is Counting Sort Stable?
Yes, as long as you do the placement step from right to left, like our code does. Stable means equal values keep the order they had in the input. With plain numbers you'd never notice, because one 3 looks just like any other 3. It matters when each value carries extra data. Say you sort students by grade:
[("Maya", 3), ("Leo", 2), ("Sam", 3)] → [("Leo", 2), ("Maya", 3), ("Sam", 3)]Maya and Sam both have a 3, and Maya stays ahead of Sam because she came first. If you walked the list left to right in the placement step, Sam would jump ahead of Maya. This stability is also what lets counting sort act as a building block inside radix sort.
Counting Sort vs. Other Sorting Algorithms
| Algorithm | Best | Average | Worst | Extra space | Stable? |
|---|---|---|---|---|---|
| Bubble sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection sort | O(n²) | O(n²) | O(n²) | O(1) | No |
| Insertion sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick sort | O(n log n) | O(n log n) | O(n²) | O(log n) average | No |
| Heap sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Counting sort | O(n + k) | O(n + k) | O(n + k) | O(n + k) | Yes |
Counting sort is the only row in that table that doesn't compare values, and it can be the fastest of the bunch when k is small. The catch is how much it asks of your data:
- Versus the comparison sorts: merge sort, quick sort and heap sort can handle anything you can compare, including strings, decimals and custom objects. Counting sort needs integer-like keys in a limited range.
- Versus merge sort: both are stable. Merge sort's extra memory depends only on
n, while counting sort's also depends on the range of values. - Versus radix sort: radix sort handles big numbers by sorting one digit at a time, and it usually uses counting sort for each digit. That way each pass only needs a small count array. It deserves an article of its own.
Where Counting Sort Is Used in the Real World
You won't call it for every sorting job, but it turns up in some handy places:
- Small-range data. Ages, exam marks, star ratings, or image brightness values from 0 to 255 are all natural fits.
- Letters and characters. Counting how often each letter appears is the same idea, and it's the trick behind quick anagram checks and sorting the characters of a string.
- Inside radix sort. Its stability makes counting sort the usual choice for sorting each digit.
- Coding interviews. Problems like "sort an array of 0s, 1s and 2s" or "sort items by frequency" are counting sort in disguise.
Advantages and Disadvantages of Counting Sort
Advantages
- Linear time,
O(n + k), when the range of values is small. - Stable, so it keeps equal items in their original order.
- Simple logic, with no tricky recursion or tree math.
- Same running time no matter how the input is arranged.
Disadvantages
- Needs a limited, known range of values.
- Uses extra memory, and a huge range can mean a huge count array.
- Only works on integers or things that can be turned into integer keys. Decimals and plain strings don't fit directly.
- Isn't in place, since it builds a separate output list.
- Negative numbers need an extra shift.
When Should You Use Counting Sort?
- Your values are integers in a small, known range, and the range isn't much bigger than the number of items.
- You have lots of duplicates, like thousands of ratings that only go from 1 to 5.
- You need a stable sort as part of a bigger algorithm, such as radix sort.
Skip it when the values are spread across a huge range, when they aren't whole numbers, or when memory is tight. And in everyday projects, your language's built-in sort is almost always the sensible pick.
Common Mistakes to Avoid
- Making the count array one slot too small. You need
max + 1slots, because counting starts at 0. - Looping left to right in the placement step. The numbers still come out sorted, but equal items lose their original order.
- Skipping the running totals. Without them you know how many of each value there are, but not where to put them.
- Feeding in negative numbers without shifting. Use the minimum-value trick shown above.
- Using it on a huge range. A few large values can blow up memory and time.
- Forgetting the empty list.
max([])raises an error, so check for an empty input first.
Try It Yourself
- Add a
print(count)after each of the three steps in the code and compare the output with the animation above. - Rewrite the function to sort tuples like
(name, grade)by grade. Then flip the placement loop to go left to right and watch equal grades swap places. - Run it on a million random numbers between 0 and 100, then on a million numbers between 0 and 10 million. Notice how much slower and hungrier the second run gets.
- Try sorting the letters of a word by using their character codes as the values.
Quick Recap
Counting sort tallies how many times each value appears, turns those tallies into running totals, then uses the totals to drop every value straight into its final position. It runs in O(n + k) time and O(n + k) space, it's stable when you place items from right to left, and it works best when the values sit in a small, known range. With this one, the series now covers bubble, selection, insertion, merge, quick, heap and counting sort.
Frequently Asked Questions
What is counting sort in simple words?
Counting sort counts how many times each value appears in a list, then uses those counts to place every value directly in its sorted position, without ever comparing two values.
What is the time complexity of counting sort?
O(n + k) in the best, average and worst cases, where n is the number of items and k is the size of the range of values.
Why is counting sort faster than O(n log n)?
The O(n log n) limit only applies to algorithms that sort by comparing items. Counting sort uses the values as array positions instead, so it never compares anything and isn't bound by that limit.
Is counting sort stable?
Yes, when the placement step walks the input from right to left. Equal values then keep the same order they had in the original list.
Is counting sort in-place?
No. It needs a count array and a separate output list, so the extra space is O(n + k).
Can counting sort handle negative numbers?
Yes, with a small tweak. Subtract the smallest value from every number when you index the count array, so the smallest value lands in slot 0.
Can counting sort sort strings or decimals?
Not directly. It needs integer keys. You can sort single characters by using their character codes, or sort records by an integer field like age or grade, but plain decimals and whole words don't fit.
What is the difference between counting sort and radix sort?
Counting sort handles each whole value at once, so it needs a slot for every possible value. Radix sort sorts numbers one digit at a time and often uses counting sort for each digit, which keeps the count array tiny even for big numbers.
When should you not use counting sort?
Avoid it when the range of values is much larger than the number of items, when the data isn't made of integers, or when memory is limited.
Does Python use counting sort?
No. Python's sorted() and list.sort() use Timsort. A counting sort written in plain Python can even lose to the built-in sort on small ranges, because the built-in one is written in C. Counting sort is mostly a great algorithm to learn from, and a handy tool for specific jobs.
Found this helpful? Run the Python code with a few different ranges and watch how the count array grows. Once you've seen a million-slot array for a three-item list, you'll never forget when not to use counting sort.
