Counting sort, radix sort & sorting in practice
Sort integers in linear time and use Python's sort with keys correctly.
By Invicly Tech, , in Data Structures & Algorithms. About 11 minutes to read.
In short
Comparison sorts cannot beat O(n log n), but sorts that use the values themselves can. Counting sort tallies each value in a range of size k for O(n + k) time, and radix sort applies a stable counting sort digit by digit. In everyday Python you use sorted with a key function, which runs Timsort.
Explained simply
Most sorts work by comparing two items: is this one smaller than that one? There is a mathematical limit to how fast that can be: about n log n comparisons. But if your items are small whole numbers, you can skip comparing altogether.
Counting sort works like sorting exam papers by grade from 0 to 100. You set up 101 piles, put each paper on the pile for its grade, and then pick up the piles in order. No two papers are ever compared. The time depends on the number of papers plus the number of piles.
Radix sort handles bigger numbers. It sorts by the last digit first, then by the second-last digit, and so on. Each round uses a stable counting sort with only 10 piles. After the last round, the numbers are fully sorted.
In everyday Python you do not write these yourself. You call sorted() and tell it what to sort by with a key function, for example sorted(people, key=lambda p: p.age). Understanding the special sorts helps you recognise when a problem can be solved in linear time.
Press Play on a diagram to walk through it one step at a time.
- O(n + k)
- Small integer range k
- Stable variant uses prefix sums
- O(d x (n + b))
- d digits in base b
- Needs a stable inner sort
- O(n log n), O(n) on runs
- Stable
- key= and reverse= options
- Step 1By ones digit
[170, 90, 802, 2, 24, 45, 75, 66]
- Step 2By tens digit
[802, 2, 24, 45, 66, 170, 75, 90]
- Step 3By hundreds digit
[2, 24, 45, 66, 75, 90, 170, 802]
- Step 4Done
3 digits, 3 stable passes, no comparisons
In depth
The n log n lower bound for comparison sorts
Any sort that learns about the order only by comparing pairs can be drawn as a decision tree. Each internal node is a comparison, each branch is its outcome, and each leaf is one final ordering. There are n! possible orderings of n distinct items, so the tree needs at least n! leaves.
A binary tree of height h has at most 2^h leaves, so h >= log2(n!). Using Stirling's approximation, log2(n!) is about n log2 n - 1.44n, which is Omega(n log n). The height is the worst-case number of comparisons, so no comparison sort can beat this.
For n = 10, log2(10!) is about 21.8, so at least 22 comparisons are needed in the worst case. Merge sort and heap sort achieve O(n log n), so they are optimal up to constants. Counting and radix sort escape the bound because they never compare items; they use the values as array indexes.
- n! possible orderings need log2(n!) yes/no answers
- log2(n!) is about n log2 n - 1.44n
- Using values as indexes avoids the bound
Stable counting sort with prefix sums
The simple version in the explainer rebuilds the output from counts, which loses any data attached to the keys. To sort records by an integer key and stay stable, use prefix sums.
Step 1: count how many records have each key. Step 2: turn counts into starting positions with a running total, so pos[v] is the number of records with key less than v. Step 3: walk the input from left to right, place each record at pos[key] and increase pos[key]. Records with the same key are placed in the order they appeared: stable.
(Many textbooks compute end positions and walk backwards instead; the result is the same.) Time is O(n + k) and extra space O(n + k), where k is the number of possible key values. It only pays off when k is not much larger than n. Sorting 1,000 ages in the range 0 to 120 is perfect. Sorting 1,000 values up to 10^9 would need a billion counters.
- 1Input keys
[2, 0, 2, 1, 3, 0]
- 2Count
count = [2, 1, 2, 1]
- 3Start positions
pos = [0, 2, 3, 5]
- 4Place in order
Each record goes to pos[key], then pos[key] += 1.
- 5Output
[0, 0, 1, 2, 2, 3], equal keys in input order
LSD radix sort
Least significant digit (LSD) radix sort processes digits from the right. Each pass sorts the whole list by one digit using a stable counting sort with b buckets (the base). After pass i, the list is sorted by its last i digits. Stability is the reason this works: when two numbers tie on the current digit, their order from earlier passes, which reflects the lower digits, is kept.
With d digits in base b, the time is O(d (n + b)). For 32-bit unsigned integers in base 256, d = 4 passes, each with 256 buckets, so the sort is linear in n. Choosing a larger base means fewer passes but more buckets.
Negative numbers need care: sort by value plus an offset, or split negatives and positives. Strings of equal length can be radix sorted character by character from the right. Most significant digit (MSD) radix sort goes left to right and recurses into each bucket, which suits variable-length strings.
- Time O(d (n + b)), space O(n + b)
- The inner sort must be stable
- 32-bit ints: 4 passes of base 256
Sorting in practice: key functions and Timsort
Python's list.sort() sorts in place and returns None. sorted() returns a new list and accepts any iterable. Both take key= and reverse=. The key function is called exactly once per item, and the results are compared. That is faster than an old-style comparison function, which would be called O(n log n) times. Use functools.cmp_to_key if you truly need pairwise logic.
The sort is guaranteed stable, even with reverse=True. So multi-key sorts can be done in passes: sort by the secondary key, then by the primary. Or use a tuple key: key=lambda p: (-p.age, p.name) sorts by age descending, then name ascending. Negation only works for numbers; for strings, use two stable passes with reverse.
operator.itemgetter(1) and operator.attrgetter('age') are fast, readable key functions. Timsort is O(n log n) worst case and O(n) on data that is already sorted or made of a few sorted runs.
- list.sort() is in place and returns None
- key is called once per item
- Stable even with reverse=True
Learn it in 4 short steps
About 40m each. Track them with a timer in your plan.
- 1Implement counting sort~40m
- 2Implement LSD radix sort~40m
- 3Explain the comparison sort lower bound~40m
- 4Sort with key functions and Timsort~40m
Key points
- Comparison sorting needs Omega(n log n) comparisons in the worst case.
- Counting sort is impractical when the value range k is much larger than n.
- Python's sort is stable, so you can sort by secondary key first, then primary.
- key functions are called once per element, cheaper than custom comparisons.
Key terms
Tap a card to flip it. 0/4 known
Examples
def counting_sort(a, max_val): # O(n + k)
counts = [0] * (max_val + 1)
for x in a:
counts[x] += 1
out = []
for v, c in enumerate(counts):
out.extend([v] * c)
return out
print(counting_sort([3, 1, 4, 1, 5], 5)) # [1, 1, 3, 4, 5]
people = [('ana', 31), ('bo', 25), ('cy', 31)]
print(sorted(people, key=lambda p: (-p[1], p[0])))Radix sort for non-negative integers
This LSD radix sort uses base 10 and a bucket list for each digit. Appending to buckets in input order and then concatenating them is a stable counting sort. The loop runs once per digit of the largest number. For [170, 45, 75, 90, 802, 24, 2, 66] it makes three passes and prints the sorted list.
def radix_sort(a, base=10):
if not a:
return a
exp, biggest = 1, max(a)
while biggest // exp > 0:
buckets = [[] for _ in range(base)]
for x in a:
buckets[(x // exp) % base].append(x)
a = [x for b in buckets for x in b]
exp *= base
return a
print(radix_sort([170, 45, 75, 90, 802, 24, 2, 66]))
# [2, 24, 45, 66, 75, 90, 170, 802]Multi-key sorting with stable passes
We want employees by department ascending, and inside each department by salary descending, and for equal salaries by name ascending. A tuple key handles numbers with negation. When a field cannot be negated (like a string in descending order), do stable passes from the least important key to the most important.
from operator import itemgetter
staff = [('ana', 'ops', 70), ('bo', 'dev', 90),
('cy', 'dev', 90), ('di', 'ops', 80), ('ed', 'dev', 75)]
by_tuple = sorted(staff, key=lambda s: (s[1], -s[2], s[0]))
by_passes = sorted(staff, key=itemgetter(0)) # name asc
by_passes.sort(key=itemgetter(2), reverse=True) # salary desc
by_passes.sort(key=itemgetter(1)) # dept asc
print(by_tuple == by_passes) # True
print([s[0] for s in by_tuple]) # ['bo', 'cy', 'ed', 'di', 'ana']Quick reference
- Comparison sorts need at least log2(n!), about n log2 n, comparisons in the worst case
- Counting sort: O(n + k) time and space for keys in range 0..k-1
- Stable counting sort: counts, prefix sums to start positions, place in input order
- LSD radix sort: O(d (n + b)); each pass must be stable
- list.sort() sorts in place and returns None; sorted() returns a new list
- Python's sort is stable, also with reverse=True: sort by secondary key first
- Descending numbers in a tuple key: use -value
- functools.cmp_to_key wraps an old-style compare(a, b) function
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Sort a list of words by length, and words of equal length alphabetically, with one call to sorted. Example: ['pear', 'fig', 'apple', 'kiwi'] gives ['fig', 'kiwi', 'pear', 'apple'].
- Exercise 2medium
Write counting_sort_by_key(records, key, k) that stably sorts records by an integer key in range 0..k-1 using counts and prefix sums. Example: sort [('a', 2), ('b', 0), ('c', 2), ('d', 1)] by the number.
- Exercise 3hard
Find the maximum gap between successive elements in sorted order of a list of non-negative integers in O(n) time without a comparison sort. Example: [3, 6, 9, 1] gives 3.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- If radix sort is linear, why doesn't Python use it?
- It only works directly on integers or fixed-length keys, needs extra memory, and its constant factors are high. Timsort works on any comparable objects and is very fast on real data with existing order.
- What is the difference between sort() and sorted()?
- list.sort() changes the list in place and returns None. sorted() accepts any iterable and returns a new list, leaving the original unchanged.
- How do I sort in descending order by one field and ascending by another?
- For numbers, negate in a tuple key, like key=lambda x: (-x.score, x.name). Otherwise, sort in stable passes from the least important key to the most important, using reverse=True where needed.