Sort Bounded Integers with Counting Sort
Core idea
Counting sort counts occurrences for each integer key in a known compact range. Emit each key as many times as it occurs. For n values and k possible keys, this version takes O(n+k) time and O(k) auxiliary counts plus the output. An offset handles negative keys. It sorts scalar keys; stable record sorting additionally needs cumulative positions.
counts = [0]*4for x in [3, 1, 3, 0]: counts[x] += 1print(counts)print([x for x,c in enumerate(counts) for _ in range(c)])The zero count skips absent keys; repeated keys are emitted twice.
Offset signed keys
a = [-2, 1, -2, 0]lo, hi = -2, 1counts = [0]*(hi-lo+1)for x in a: counts[x-lo] += 1print([i+lo for i,c in enumerate(counts) for _ in range(c)])Subtract lo to index the array, then add it back when emitting values.
Common mistake
Never allocate a count array for an unchecked huge key range. Reject keys outside the contract; negative indices otherwise silently count the wrong bucket.
Practice
Count keys in [-3, 3] after checking the range. Test empty input and an invalid key.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Counting sort
Check your understanding of counting sort.
What is printed?
c=[0,2,1]print([i for i,n in enumerate(c) for _ in range(n)])What is printed?
lo=-3print(-1-lo)When is counting sort attractive?
Cost of scalar counting sort?