Algorithms
Counting Sort
Sort without comparing — O(n+k) when keys are small integers
Counting sort doesn't compare any pair of elements. Instead, it counts how many times each value appears, then writes them back in order. Runs in O(n + k) where k is the range of values — beats the Ω(n log n) lower bound on comparison sorts when k is small. Stable, simple, and the foundation of radix sort.
- TimeO(n + k)
- SpaceO(n + k)
- StableYes
- In-placeNo
- Comparison-basedNo
- Best forBounded integer keys
Interactive visualization
Press play, or step through manually. The visualization is yours to drive — try it before reading on.
Watch the 60-second explainer
A condensed visual walkthrough — narrated, captioned, under a minute.
How counting sort works
Three phases:
- Count. Scan the input. For each element
x, incrementcount[x]. The bucket arraycounthas one slot per possible value in the range. - Cumulative. Replace each
count[i]with the running totalcount[0] + count[1] + ... + count[i]. Nowcount[x]tells you the position immediately after where the lastxbelongs in the output. - Write back. Iterate the input right-to-left. For each
x, decrementcount[x], then placexatoutput[count[x]]. Right-to-left is what makes the sort stable.
Concrete walkthrough. Sort [3, 1, 4, 1, 5, 2, 6, 4, 3, 1] with range 0..6:
Phase 1 (count): [0, 3, 1, 2, 2, 1, 1]
(three 1s, one 2, two 3s, two 4s, one 5, one 6)
Phase 2 (cumulative): [0, 3, 4, 6, 8, 9, 10]
(three slots for values ≤ 1, six for ≤ 3, etc.)
Phase 3 (write back): [1, 1, 1, 2, 3, 3, 4, 4, 5, 6]
The key insight: after Phase 2, count[x] tells you exactly how many output slots are reserved for values ≤ x. So the position of the last x is at count[x] - 1. Decrementing as you write places duplicates in reverse-input order — but iterating input right-to-left flips that back into stable order.
When to use counting sort
- Small bounded integer keys. Ages (0-150), grades (0-100), bytes (0-255), DNA bases (4 values), pixel intensities (0-255 or 0-65535). Anywhere k is much smaller than n, counting sort is the fastest option available.
- As a subroutine of radix sort. Each digit pass uses a counting sort with k = 10 (or k = 256 for byte-by-byte). The whole pipeline turns O(n log n) comparison sorting into O(d·n) for d-digit keys.
- Histogram problems. If you need both the sorted output and the frequency distribution, counting sort gives you both in one pass — the bucket array IS the histogram.
- Stable sort by a small key. If you're sorting records by a small integer field, counting sort preserves the relative order of records with equal keys for free.
Counting sort vs comparison sorts
| Counting sort | Quick sort | Merge sort | |
|---|---|---|---|
| Time (avg) | O(n + k) | O(n log n) | O(n log n) |
| Space | O(n + k) | O(log n) | O(n) |
| Stable | Yes | No | Yes |
| Comparison-based | No | Yes | Yes |
| Key requirements | Bounded integers | Any comparable | Any comparable |
| Cache locality | Excellent (sequential) | Excellent | Poor (writes scattered) |
| Crossover with quicksort | Wins when k < n log n | — | — |
For n = 1,000,000 and k = 256 (byte values), counting sort is about 100× faster than quicksort in raw operations and uses similar memory. For n = 100 and k = 1,000,000 (sparse 32-bit values), quicksort wins because the bucket array dominates.
Pseudo-code
function countingSort(arr, k): // values are 0..k-1
count = new array of size k, filled with 0
output = new array of size arr.length
// Phase 1: count occurrences
for x in arr:
count[x] += 1
// Phase 2: cumulative counts
for i from 1 to k - 1:
count[i] += count[i - 1]
// Phase 3: stable writeback (right-to-left)
for i from arr.length - 1 down to 0:
x = arr[i]
count[x] -= 1
output[count[x]] = x
return output
JavaScript implementation
function countingSort(arr, max) {
const count = new Array(max + 1).fill(0);
const output = new Array(arr.length);
// Phase 1: count
for (const x of arr) count[x]++;
// Phase 2: cumulative
for (let i = 1; i <= max; i++) count[i] += count[i - 1];
// Phase 3: stable writeback
for (let i = arr.length - 1; i >= 0; i--) {
const x = arr[i];
output[--count[x]] = x;
}
return output;
}
// countingSort([3,1,4,1,5,2,6,4,3,1], 6)
// → [1, 1, 1, 2, 3, 3, 4, 4, 5, 6]
Python implementation
def counting_sort(arr, max_val):
count = [0] * (max_val + 1)
output = [0] * len(arr)
# Phase 1: count occurrences
for x in arr:
count[x] += 1
# Phase 2: cumulative counts
for i in range(1, max_val + 1):
count[i] += count[i - 1]
# Phase 3: stable writeback (right-to-left for stability)
for i in range(len(arr) - 1, -1, -1):
x = arr[i]
count[x] -= 1
output[count[x]] = x
return output
Handling negative keys and offsets
Counting sort assumes keys start at 0. For arbitrary integer ranges, find the min and max in a pre-pass and offset:
function countingSortRange(arr) {
if (!arr.length) return arr;
let min = arr[0], max = arr[0];
for (const x of arr) { if (x < min) min = x; if (x > max) max = x; }
const k = max - min + 1;
const count = new Array(k).fill(0);
const output = new Array(arr.length);
for (const x of arr) count[x - min]++;
for (let i = 1; i < k; i++) count[i] += count[i - 1];
for (let i = arr.length - 1; i >= 0; i--) {
output[--count[arr[i] - min]] = arr[i];
}
return output;
}
The pre-scan adds O(n) but doesn't change the asymptotic cost. Offset arithmetic adds one subtraction per element — negligible.
Common bugs and edge cases
- Allocating a bucket array proportional to max value, not range. Sorting
[1000000, 1000001, 1000002]with a max-value-sized bucket allocates 1M slots for 3 elements. Always allocatemax - min + 1, notmax + 1. - Iterating input left-to-right in the writeback phase. This breaks stability — duplicates end up in reverse input order. Always iterate right-to-left when using the cumulative-count technique.
- Off-by-one in cumulative. The cumulative array tells you the position one past where the last element of value x belongs. Decrement before writing, not after, or you'll write past the end of the output.
- Using counting sort for floats or strings. The whole technique requires integer keys. For strings, use radix sort byte-by-byte or fall back to a comparison sort.
- Trying to make it in-place. True counting sort needs the output buffer; in-place variants exist but are no longer stable and are usually slower than just paying the O(n) extra memory.
Frequently asked questions
Why is counting sort O(n + k)?
Three passes. First pass counts occurrences of each value into a bucket array of size k — O(n) for the input scan plus O(k) to allocate the buckets. Second pass converts counts to cumulative positions — O(k). Third pass writes elements to output positions — O(n). Total work: O(n) + O(k) = O(n + k).
How does counting sort beat the Ω(n log n) bound?
That lower bound applies only to *comparison* sorts. Counting sort never compares two elements; it just looks at each element's value and increments a counter. The bound doesn't apply because the algorithm exploits structure in the keys (integer values in a known range) that comparison sorts ignore.
When is counting sort the wrong choice?
When k is large or unbounded. For sorting 64-bit integers (k = 2^64), the bucket array would need 18 quintillion slots. For floating-point or string keys, there's no natural integer range. Use a comparison sort or radix sort instead.
What's the difference between counting sort and bucket sort?
Counting sort puts each unique value in its own bucket and counts occurrences. Bucket sort distributes values across a smaller number of buckets (each bucket holds a *range* of values), then sorts each bucket independently — typically with insertion sort. Counting sort is exact; bucket sort is a lossy partitioning that needs a per-bucket sort to finish.
How is counting sort related to radix sort?
Radix sort applies counting sort one digit at a time, from least-significant to most-significant. Each pass is a stable counting sort with k = 10 (decimal) or k = 2 (binary). Total cost: O(d × (n + k)) where d is the number of digits. That's how radix sort sorts 32-bit integers in linear time despite the value range being 4 billion.
Why must counting sort be stable?
Stability isn't optional — it's required for correctness in applications that sort by multiple keys (radix sort, lexicographic ordering of records). The cumulative-count writeback uses output indices that depend on both the value and the original input order; doing it stably is straightforward (iterate input right-to-left when assigning positions), doing it unstably breaks downstream radix sort.