Counting sort and radix sort
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
"Why comparison sorts can't beat n log n" proves a floor for sorts that only compare. Counting sort steps around it: it never compares two items, it uses each item's small whole-number key as a list index. Watch six numbers get counted, totalled and dropped into place by their ones digit, then sorted fully by radix sort, one stable pass per digit. It builds on the Software lessons on sorting (insertion sort, merge sort, Timsort).
Sort by a small key
Six two-digit numbers sit in row A. First we sort them by their ones digit only: the key. Every key here is 0 to 3, so k = 4. Counting sort never compares two numbers. It uses each key as an array index.
row A 31 12 23 10 32 21 key 1 2 3 0 2 1 (ones digit) n = 6 numbers, k = 4 possible keys (0..3) key(x) = x % 10
اقرأ الدرس خطوة بخطوة
Sort by a small key
Six two-digit numbers sit in row A. First we sort them by their ones digit only: the key. Every key here is 0 to 3, so k = 4. Counting sort never compares two numbers. It uses each key as an array index.
row A 31 12 23 10 32 21 key 1 2 3 0 2 1 (ones digit) n = 6 numbers, k = 4 possible keys (0..3) key(x) = x % 10Count each key
Line 4 walks the list once and adds 1 to count[key] for each number. The keys 1, 2, 3, 0, 2, 1 give count = [1, 2, 2, 1]: one key 0, two 1s, two 2s and one 3.
for x in a: count[key(x)] += 1 31 key 1 count = [0, 1, 0, 0] 12 key 2 count = [0, 1, 1, 0] 23 key 3 count = [0, 1, 1, 1] 10 key 0 count = [1, 1, 1, 1] 32 key 2 count = [1, 1, 2, 1] 21 key 1 count = [1, 2, 2, 1]Running totals
Lines 5 and 6 add each counter to the one before it. Now count[d] says how many keys are d or less: [1, 2, 2, 1] becomes [1, 3, 5, 6]. So the numbers with key d end just before slot count[d].
for d in range(1, k): count[d] += count[d - 1] start count = [1, 2, 2, 1] d = 1 count = [1, 3, 2, 1] d = 2 count = [1, 3, 5, 1] d = 3 count = [1, 3, 5, 6] keys ≤ 0: 1, ≤ 1: 3, ≤ 2: 5, ≤ 3: 6Place from the back
Line 8 walks the list backwards. For each number, count[key] goes down by 1 and the number drops into that slot of row B. 21 lands in slot 2, 32 in slot 4, 10 in slot 0, and so on.
for x in reversed(a): count[key(x)] -= 1; out[count[key(x)]] = x 21 key 1 → slot 2 count = [1, 2, 5, 6] 32 key 2 → slot 4 count = [1, 2, 4, 6] 10 key 0 → slot 0 count = [0, 2, 4, 6] 23 key 3 → slot 5 count = [0, 2, 4, 5] 12 key 2 → slot 3 count = [0, 2, 3, 5] 31 key 1 → slot 1 count = [0, 1, 3, 5] row B 10 31 21 12 32 23Ties keep their order
Row B is sorted by ones digit: 10, 31, 21, 12, 32, 23. Equal keys kept their input order: 31 still comes before 21, and 12 before 32. A sort that keeps ties in their input order is called stable.
row A 31 12 23 10 32 21 row B 10 31 21 12 32 23 key 1: 31 then 21 (same order as row A) key 2: 12 then 32 (same order as row A) placing from the back fills each key's slots from the right, so ties never swapΘ(n + k), no comparisons
Two loops touch each of the n numbers and one touches each of the k counters, so it takes Θ(n + k) time. It never compares two numbers, so the n log n bound for comparison sorts does not apply. But k must stay small.
line 3 for x in a n times line 5 for d in range(1, k) k - 1 times line 8 for x in reversed(a) n times time Θ(n + k) extra memory: count (k cells) + out (n cells) here: n = 6, k = 4 keys up to 2**32 would need about 4.3 billion countersNext digit: the tens
Radix sort handles bigger keys one digit at a time, ones digit first. Row B is already sorted by ones. Now run the same counting sort on row B again, with the tens digit as the key, writing back into row A.
row B 10 31 21 12 32 23 key 1 3 2 1 3 2 (tens digit) key(x) = x // 10 % 10 pass 1 sorted by ones, pass 2 sorts by tensCount and total the tens
The tens digits of row B are 1, 3, 2, 1, 3, 2. Counting gives [0, 2, 2, 2]: no number has tens digit 0. Running totals turn that into [0, 2, 4, 6].
count the keys 10 key 1 count = [0, 1, 0, 0] 31 key 3 count = [0, 1, 0, 1] 21 key 2 count = [0, 1, 1, 1] 12 key 1 count = [0, 2, 1, 1] 32 key 3 count = [0, 2, 1, 2] 23 key 2 count = [0, 2, 2, 2] running totals d = 1 count = [0, 2, 2, 2] d = 2 count = [0, 2, 4, 2] d = 3 count = [0, 2, 4, 6]Place from the back again
Walk row B backwards. Each number takes count[key] − 1 as its slot in row A: 23 lands in slot 3, 32 in slot 5, 12 in slot 1. Row A ends as 10, 12, 21, 23, 31, 32: sorted.
23 key 2 → slot 3 count = [0, 2, 3, 6] 32 key 3 → slot 5 count = [0, 2, 3, 5] 12 key 1 → slot 1 count = [0, 1, 3, 5] 21 key 2 → slot 2 count = [0, 1, 2, 5] 31 key 3 → slot 4 count = [0, 1, 2, 4] 10 key 1 → slot 0 count = [0, 0, 2, 4] row A 10 12 21 23 31 32Why the order holds
31 and 32 share a tens digit, so they tied in pass 2. Stability kept them in their pass 1 order, which was by ones digit. So every tie is broken by the ones digit: that is numeric order. An unstable pass might swap them.
after 1 10 31 21 12 32 23 after 2 10 12 21 23 31 32 tens 1: 10 then 12 (order from pass 1) tens 2: 21 then 23 tens 3: 31 then 32 ones digit first, most significant digit lastRadix sort's cost
d digits means d passes of counting sort: Θ(d(n + k)) time. A 32-bit integer is four 8-bit digits, so 4 passes with 256 counters each, however big n is. With d fixed and k small, that is linear in n.
time Θ(d · (n + k)) here: d = 2 passes, n = 6, k = 4 32-bit keys as 8-bit digits: d = 4, k = 256 4 · (n + 256) steps of counting work def radix_sort(a, d, k=10): for p in range(d): a = counting_sort(a, lambda x: x // k**p % k, k) return a
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01Counting sort is run on the keys [2, 0, 2, 1] with k = 3. What is the count list after the running totals?
The counts are [1, 1, 2]: one 0, one 1, two 2s. Each counter then adds the one before it: 1, 1 + 1 = 2, 2 + 2 = 4. count[d] is now how many keys are d or less.
02Why does counting sort not break the Ω(n log n) lower bound for comparison sorts?
The bound counts comparisons. Counting sort reads each key and uses it as a list index instead, which is outside that model. The price is that keys must be small whole numbers.
03What does it mean for a sort to be stable?
Stable means ties keep their input order. Counting sort is stable because it places items from the back of the list into each key's slots from the right.
04Radix sort sorts [31, 12, 23, 10, 32, 21] by the ones digit, then by the tens digit. Why must the tens pass be stable?
After the ones pass, 31 comes before 32. They tie on the tens digit, so only stability keeps 31 first. An unstable tens pass could put 32 before 31.
05You radix sort n 32-bit integers, one 8-bit digit at a time. How many passes are there, and how many counters does each use?
32 bits split into 8-bit digits gives d = 4 digits, and an 8-bit digit has 2⁸ = 256 values, so k = 256. Total time Θ(4(n + 256)), which is linear in n.
المسرد
- Key
- The whole number a sort orders items by. In counting sort it must be between 0 and k − 1.
- k
- How many different key values there can be. Counting sort needs one counter for each.
- Counting sort
- A sort that counts how many items have each key, takes running totals, and uses them as slot numbers. Θ(n + k) time, no comparisons.
- Running total
- A counter plus all the counters before it. Here count[d] becomes how many keys are d or less.
- Stable sort
- A sort that keeps items with equal keys in their input order.
- Radix sort
- Sorts numbers one digit at a time, least significant digit first, with a stable sort (usually counting sort) on each digit.
- Digit
- One position of a number in some base: the ones or tens digit in base 10, or one 8-bit byte in base 256.
- Comparison sort
- A sort that learns about its input only by comparing two items at a time. These need Ω(n log n) comparisons in the worst case.
الملاحظات والمصادر
- Every digit in this example is 0, 1, 2 or 3, so k = 4 counters are enough. Ordinary decimal radix sort uses k = 10, one counter per digit, and the code below takes k as a parameter.
- The code follows COUNTING-SORT in CLRS §8.2: running totals, then placing from the back. Sedgewick and Wayne's key-indexed counting turns the counts into starting slots and places from the front instead. Both are stable and take time proportional to n + k.
- The Ω(n log n) bound in "Why comparison sorts can't beat n log n" counts comparisons. Counting sort reads keys as array indices and makes no comparisons, so it sits outside that model. It is not a contradiction.
- The code is real Python 3. counting_sort([31, 12, 23, 10, 32, 21], lambda x: x % 10, 4) returns [10, 31, 21, 12, 32, 23], and radix_sort([31, 12, 23, 10, 32, 21], 2) returns [10, 12, 21, 23, 31, 32].
- Counting sort is not in place: it needs the count list (k cells) and a new output list (n cells). Radix sort reuses them on every pass.
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 5: Linear Sorting (notes PDF)
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 5 page
- Sedgewick and Wayne, Algorithms 4th ed., §5.1 String Sorts
- Sedgewick and Wayne, lecture slides 5.1 String Sorts (key-indexed counting, LSD radix sort)
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §8.2 Counting sort, §8.3 Radix sort
- Python Sorting Techniques: sort stability and sorting in several passes
- Python built-in functions: reversed() and sorted()
- Python Language Reference: binary arithmetic operations (// and %)
اختبار يتاح بعد الخطوة الأخيرة.