Short answer: Counting sort histograms keys that lie in 0, 1, …, k−1, turns the histogram into prefix totals, and writes each record into the slot those totals name. The time and the extra memory are Θ(n+k). Writing from the end of the input and decrementing the total makes the sort stable. It is the digit sort inside radix sort, and it is a full sort whenever k is not much larger than n.
What the problem actually asks
Comparison sorting needs Ω(n log n) comparisons. Integer keys in a bounded range can be grouped by counting, which never compares two keys with each other. The histogram says how many keys belong in each bucket. A prefix sum of that histogram says the first output index that follows every copy of a given key.
Stability matters because radix sort calls this procedure once per digit and needs equal digits to keep the order established by the previous digit.
What the algorithm guarantees
One pass counts, one pass builds prefixes, one pass writes. That is Θ(n+k) time. The count array has length k and the output array has length n. Keys outside 0..k−1 are a precondition failure, not a slower case. Negative keys are shifted by a constant only when a finite lower bound is known and k stays moderate.
The stable write scans the input from index n−1 down to 0. The prefix count[v] is the number of keys that are at most v, so the last input key with value v belongs at index count[v]−1. Decrementing count[v] leaves the previous copy of v one slot to the left. Equal keys therefore keep their input order.
The working steps
- Allocate a count array of length k, initially zero, and an output array of length n.
- For each key v, increment count[v].
- Replace count[v] with the sum of count[0] through count[v]. count[v] is now the number of keys that are ≤ v.
- For i from n−1 down to 0, let v be the key at i. Write record i to output index count[v]−1, then decrement count[v].
- Copy the output back if the caller needs the result in the original array.
The linear bound holds when k is Θ(n), or at least small enough that a length-k array is acceptable. A 64-bit key with k = 2^64 is a different problem. Radix sort then counts one digit, whose range is chosen to fit in memory.
Approaches that look simpler and fail
| Approach | Why it fails when keys are integers in 0..k−1 |
|---|---|
| Write the output from left to right | The first copy of v takes the last slot reserved for v. Later equal keys land to its left, and the order of equals reverses. |
| Allocate the histogram and skip the prefix sum | A raw count says how many copies exist. The output index of a particular copy comes from the prefix total. |
| Use it on arbitrary comparable objects | The index into the histogram is the key itself. Objects that only support a comparison have no such index. |
| Ignore k in the cost | Time and memory both grow with the key domain. A sparse domain with a huge maximum is paid for in the count array, even if n is small. |
A comparison sort is the right tool for ordered objects with no integer rank. A digit-by-digit integer sort for large word sizes is radix sort, which calls this stable histogram once per digit.
A working example
The Bash script and the Python script counting-sort keys in 0…9. The write walks the input from the end, which is what keeps equal keys in their original order. Both print 1 2 2 4 4.
a=(4 2 2 1 4)
n=${#a[@]}
count=()
for ((v=0; v<10; v++)); do count[v]=0; done
for ((i=0; i<n; i++)); do count[a[i]]=$((count[a[i]]+1)); done
for ((v=1; v<10; v++)); do count[v]=$((count[v]+count[v-1])); done
for ((i=n-1; i>=0; i--)); do
v=${a[i]}
count[v]=$((count[v]-1))
out[count[v]]=$v
done
echo "${out[*]}"
def counting_sort(a, k=10):
count = [0] * k
for v in a:
count[v] += 1
for v in range(1, k):
count[v] += count[v - 1]
out = [0] * len(a)
for i in range(len(a) - 1, -1, -1):
v = a[i]
count[v] -= 1
out[count[v]] = v
return out
a = counting_sort([4, 2, 2, 1, 4])
assert a == [1, 2, 2, 4, 4]
print(*a)
Where it is used
Counting sort is the stable digit pass inside radix sort, and the histogram sort of a byte or a small integer key. Suffix-array construction uses those histograms. Comparison sorts are the fallback once the key is no longer a small integer.
When you can drop this algorithm
Drop counting sort when k is far larger than n and a length-k array will not fit, or when keys are not integers in a known range. Use radix sort for fixed-width integers and a comparison sort for general keys. Keep counting sort when the range is small, including as the stable inner sort of one radix digit.
Why this stays published
We publish this so a search for counting sort returns the backward write that makes the histogram stable. Counting sort orders integer keys in 0..k−1 in Θ(n+k) time, and scanning the input from the end is what keeps equal keys in their original order.
本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。
