Counting Sort、Radix Sort 与 Sorting Lower Bounds
Algorithms:Counting Sort, Radix Sort and Sorting Lower Bounds
本文逐段翻译 MIT 6.006 Fall 2011 Lecture 7《Counting Sort, Radix Sort, Lower Bounds for Sorting》,先在 comparison model 中证明 searching 与 sorting 的 lower bounds,再说明为什么 integer keys 可以绕开 comparison lower bound,并构造 counting sort 与 radix sort。
TL;DR
- Comparison model:input items 被当作 black boxes,algorithm 只能通过
<、>、≤等 comparisons 获取信息。 - Lower bound:在 comparison model 中,searching
n个预处理 items 至少需要Ω(log n);sortingn个 items 至少需要Ω(n log n)。 - Counting sort:当 keys 是范围为
0..k-1的 small integers 时,用 array of lists 按 key 分桶,时间为Θ(n + k)。 - Radix sort:把整数写成 base
b的d = log_b k位,从 least significant digit 到 most significant digit,使用 stable counting sort,时间为Θ((n+b)log_b k)。 - 关键边界:linear-time sorting 并没有违反 comparison lower bound,因为 counting/radix sort 使用了 integer key 的额外结构,而不只是比较 keys。
目录
| 章节 | 说明 |
|---|---|
| Lecture 7:Linear-Time Sorting | comparison model 与线性排序的动机 |
| Comparison model | input、允许的操作与 cost model |
| Decision tree | 用 decision tree 表示 comparison algorithm |
| Searching lower bound | Ω(log n) 的信息论证明 |
| Sorting lower bound | Ω(n log n) 的 permutation 证明 |
| Counting sort | small integer keys 的线性排序 |
| Radix sort | stable digit sorting 与复杂度 |
| 复杂度总结 | comparison 与 integer sorting 的适用边界 |
| 小结 | 本讲要点 |
Lecture 7:Linear-Time Sorting
前几讲介绍了 insertion sort、merge sort、heap sort、BST sort 和 AVL sort。它们都依赖某种形式的 key comparison。一个自然的问题是:
只通过比较 keys,sorting 最快能做到什么程度?
本讲先回答这个问题,再讨论对 small integer keys 使用更多信息后,如何得到 linear-time sorting algorithms:
Comparison model:searching Ω(log n),sorting Ω(n log n)
Integer keys:counting sort 与 radix sort 可以达到 O(n)(在适当参数下)
Comparison model
在 comparison model 中,input items 被视为 black boxes,或者更抽象地视为 ADTs。algorithm 不能读取 item 的内部表示,只能调用 comparison operations:
<、>、≤、≥、= 等
时间成本只计算 comparisons 的数量。这个模型适用于 keys 之间只有 ordering information 可用的情形,例如任意对象、字符串或没有可利用数值编码的 records。
comparison model 的重要性在于:algorithm 不可能从 key 的 bit pattern、digit、数值范围或 memory representation 中得到额外信息。后面的 counting sort 和 radix sort 正是通过利用这些额外信息,突破 comparison-only 的 lower bound。
Decision tree
任何 comparison algorithm 都可以针对固定的 n 描述为一棵 decision tree:
- internal node 表示一次 binary decision,例如
A[1] < x?; - edge 表示 comparison 的一种 outcome;
- leaf 表示 algorithm 已经得到 output 并结束;
- root-to-leaf path 表示某个 input 上的一次 algorithm execution;
- path length 是该次 execution 的 running time;
- tree height 是 worst-case running time。
Binary search 的例子
对一个包含 3 个已排序 elements 的 array,binary search 可以先比较中间位置,再根据结果比较左侧或右侧:
A[1] < x ?
/ \
NO YES
A[0] < x ? A[2] < x ?
/ \ / \
NO YES NO YES
x ≤ A[0] ... A[1] < x ≤ A[2] ...
每一条从 root 到 leaf 的 path 都是一种可能的 search execution。decision tree 甚至比严格的 comparison model 更强,因此在这个模型上证明出的 lower bound 同样适用于 comparison algorithms。
Searching lower bound
假设 array A 中有 n 个预处理 items,需要判断 query x 是否等于某个 A[i],或确定它应该位于哪个位置。
至少有 n 种可能的成功答案:x = A[0]、x = A[1],直到 x = A[n-1]。decision tree 必须至少有 n 个 leaves,因为不同答案不能共享同一个最终 output:
#leaves ≥ n
decision tree 是 binary tree。height 为 h 的 binary tree 最多有 2^h 个 leaves,因此:
2^h ≥ n
h ≥ log₂ n
于是,在 comparison/decision-tree model 中,searching n 个预处理 items 需要:
Ω(log n)
这说明 binary search 和 balanced BST search 都达到了 asymptotically optimal 的 worst-case bound。
Sorting lower bound
sorting 的 output 不只是“找到某个 item”,而是必须确定所有 items 的相对顺序。假设 input 中的 keys 互不相同,那么 n 个 items 可能形成 n! 种不同的 permutations;每一种 permutation 都可能是正确的 sorted output。
因此 sorting decision tree 至少需要 n! 个 leaves:
#leaves ≥ n!
如果 tree height 为 h,则:
2^h ≥ n!
h ≥ log₂(n!)
估计 log(n!)
展开 factorial:
log(n!) = log 1 + log 2 + ... + log(n-1) + log n
为了得到 lower bound,只保留后半段的 terms。对 i = ⌈n/2⌉ ... n,每一项都至少是 log(n/2),而这样的 terms 数量是 n/2 左右:
log(n!)
≥ ∑_{i=n/2}^n log i
≥ ∑_{i=n/2}^n log(n/2)
= (n/2) log(n/2)
= Ω(n log n)
所以任何只使用 comparisons 的 sorting algorithm 都满足:
worst-case time = Ω(n log n)
这解释了为什么 merge sort、heap sort 和 AVL sort 的 Θ(n log n) worst-case bound 已经是 comparison model 下的最优数量级。
更精确的估计
Stirling’s formula 给出:
n! ~ √(2πn) · (n/e)^n
取 logarithm:
log(n!) = n log n - (log e)n + 1/2 log n + O(1)
= n log n - O(n)
因此 lower bound 不只是数量级上的直觉,而是由 permutation 数量严格决定的。
Counting sort
comparison lower bound 的前提是 keys 是 black boxes,只能通过比较获得信息。如果 n 个 keys 是适合放入 machine word 的 integers,且都属于:
{0, 1, ..., k - 1}
那么可以直接使用 integer key 做 array indexing,而不必逐个比较。特别地,当 k = n^{O(1)} 时,可以在 O(n) 时间内 sorting。
用 lists 分桶
最直接的 counting sort 版本建立一个包含 k 个 empty lists 的 array L。遍历 input A,把每个 item 放进由其 key 指定的 bucket:
L = [empty_list() for _ in range(k)]
for j in range(n):
L[key(A[j])].append(A[j])
output = []
for i in range(k):
output.extend(L[i])
这里的 L[key(A[j])] 是 random access,因为 key 是 integer;每次 append 视为 O(1)。第一轮把 n 个 items 分桶,需要 O(n);第二轮访问 k 个 lists,并输出全部 items,需要:
O(∑ᵢ (1 + |L[i]|)) = O(k + n)
因此:
Counting sort:Θ(n + k) time
Θ(n + k) space
直觉
如果 item 就是 key 本身,counting sort 可以只记录每个 key 出现了多少次,然后按 key 顺序输出对应数量的 copies。真实 item 通常比 key 更复杂,不能只输出 key;使用 lists 可以把完整 item 保留下来。
CLRS 给出了更紧凑的 counting sort implementation:使用 counters 和 output array,而不是每个 key 建一个 list。它的 asymptotic time bound 仍然是 Θ(n + k)。
何时适合 counting sort
counting sort 的时间依赖 k,而不是只依赖 n:
k = O(n) → Θ(n + k) = Θ(n)
k = n² → Θ(n + k) = Θ(n²),不再是线性
所以 counting sort 适合 key range 小且相对密集的场景。若 keys 的 maximum 很大但每个 key 只占很少一部分范围,直接建立 k 个 buckets 会浪费空间。
Radix sort
counting sort 直接处理 key range 0..k-1。radix sort 的想法是把每个 integer 写成 base b 的 d 位:
d = ⌈log_b k⌉
每一位属于 {0, 1, ..., b - 1}
不直接按整个 integer 分桶,而是依次按 digit sorting:
1. 按 least significant digit sorting;
2. 再按下一个 digit sorting;
3. 一直到 most significant digit。
每一轮 digit sorting 都可以使用 counting sort,因为 digit 的 range 只有 0..b-1。
为什么必须 stable
每一轮 sorting 必须是 stable 的:对于 digit 相同的 items,要保持它们在上一轮中的 relative order。
上一轮已经按低位 digit 排好序;本轮按高一位 digit 分组时,如果把相同高位 digit 的 items 随意打乱,就会破坏低位排序结果。stable sort 能保证:在当前 digit 相同的 items 中,低位 digit 的顺序仍然保留。
两位数字的例子
假设按两个 decimal digits sorting。先按个位,再按十位:
input
↓ stable sort by ones digit
按个位有序
↓ stable sort by tens digit
最终按两位 integer 有序
对每个 digit 使用 counting sort 后,所有 items 会按当前 digit 分桶;stable output 保留同一 bucket 内上一轮的顺序。因此到达 most significant digit 后,整个 integer 已经有序。
复杂度
每一位使用 counting sort,成本为:
Θ(n + b)
总共有 d = ⌈log_b k⌉ 位,所以 radix sort 的总时间为:
Θ((n + b)d) = Θ((n + b) log_b k)
在忽略常数和取整的情况下,选择 b = n 可以得到:
Θ((n + n) log_n k) = Θ(n log_n k)
如果 k ≤ n^c,则 log_n k ≤ c,于是:
Radix sort:O(n)
base 的选择
b 越小,digit 数量 log_b k 越多;b 越大,每一轮 counting sort 的 bucket 数量越多。总复杂度:
Θ((n + b) log_b k)
反映了两者之间的 trade-off。实际选择还要考虑 cache、word size、digit extraction cost 和 stable output 的 memory layout。
复杂度总结
| Algorithm / model | 适用条件 | 时间复杂度 | 额外空间 |
|---|---|---|---|
| Comparison sorting | 只能比较 keys | Ω(n log n) lower bound | 取决于实现 |
| Merge sort | 任意可比较 keys | Θ(n log n) | Θ(n) |
| Heap sort | 任意可比较 keys | Θ(n log n) | Θ(1) |
| AVL sort | 任意可比较 keys | Θ(n log n) | Θ(n) |
| Counting sort | integer keys 0..k-1 | Θ(n + k) | Θ(n + k) |
| Radix sort | integer keys,可按 digit 提取 | Θ((n+b)log_b k) | 每轮需要 stable output |
comparison lower bound 并没有被 counting sort 或 radix sort 违反。lower bound 只约束 comparison model;integer sorting 使用了 key 的 representation、有限 range 和 digit structure,因此不在同一个 model 中。
小结
decision tree 把 comparison algorithm 的每次 execution 表示成一条 root-to-leaf path。search 至少需要区分 n 种答案,因此有 Ω(log n) lower bound;sorting 至少需要区分 n! 种 permutations,因此有 Ω(n log n) lower bound。
当 keys 是 small integers 时,可以用 array indexing 直接访问 key 对应的位置。counting sort 通过 buckets 在 Θ(n+k) 内完成 sorting;radix sort 把整数分解成 digits,依次使用 stable counting sort,并在 k ≤ n^c 等条件下达到 O(n)。算法的 asymptotic bound 始终依赖 computation model 和 input assumptions。
参考资料
评论 (0)