目录
正在加载目录…
正在阅读专栏 Algorithms:CLRS + MIT 6.006 第 3 篇 · 共 24 篇 · 13%

Sorting:Insertion Sort、Merge Sort 与递推树分析

发布于 2026-09-18 17:31 · 最后编辑于 2026-09-18 17:31 · 版本 v2 · 字数 4,098 · 预计阅读 9 分钟 👁 16 次阅读

Algorithms:Insertion Sort and Merge Sort

本文逐段翻译 MIT 6.006 Fall 2011 Lecture 3《Insertion Sort, Merge Sort》,从 sorting 的应用出发,完整说明 insertion sort、binary insertion sort、merge sort、recursion tree、auxiliary space 与 asymptotic complexity。

TL;DR

  • Sorting 的价值:排序不只是为了输出有序结果;median、binary search、compression、graphics rendering 等问题会因此变简单。
  • Insertion sort:实现简单、in-place、auxiliary space 为 Θ(1),但普通版本 worst-case 为 Θ(n²)。
  • Binary insertion sort:利用已经排好序的 prefix,将 comparisons 降到 Θ(n log n);array 中移动元素仍使 swaps 保持 Θ(n²)。
  • Merge sort:通过 divide and conquer 与 two-finger merge 达到 Θ(n log n),代价是通常需要 Θ(n) auxiliary space。
  • 递推树:T(n)=2T(n/2)+cn 的每层工作量近似相同,共 1+log n 层,因此为 Θ(n log n);递推式的 non-recursive work 位于 root 或 leaves 时,结果会不同。

目录

章节说明
Lecture 3:Sortingsorting 的动机与应用
Insertion sort算法、示例、复杂度与 binary insertion sort
Merge sortmerge invariant、two-finger merge 与递推式
Recursion tree用递推树分析不同 recurrence
空间、常数与实际性能in-place、auxiliary space 与 benchmark

Lecture 3:Sorting

排序的直接应用包括 phone book、MP3 organizer 和 spreadsheet。更重要的是,一些问题在输入已排序后会变得简单:

  • Median:排序后查看中间位置即可得到 median;
  • Binary search:在 sorted array 中查找特定 item 只需 logarithmic time,而线性扫描需要 linear time;
  • Data compression:排序会把 duplicates 放在一起,可以用 item 加 frequency 表示重复内容;
  • Computer graphics:渲染 opaque objects 时常按 front-to-back,处理 transparency 时可能按 back-to-front。

排序通常接收一个 comparison function。数据可以是 numbers,也可以是 records;只要能够判断一个 record 是否小于另一个 record,就可以在同一 algorithmic framework 中排序。

Insertion sort

核心思想

对 i = 1, 2, ..., n-1,假定 A[0 ... i-1] 已经 sorted,把 A[i] 插入 prefix 中的正确位置。A[0] 只有一个元素,因此天然 sorted。

text
Insertion-Sort(A):
    for i ← 1 to n - 1:
        key ← A[i]
        j ← i - 1
        while j ≥ 0 and A[j] > key:
            A[j + 1] ← A[j]
            j ← j - 1
        A[j + 1] ← key

讲义中的实现使用 pairwise swaps;用 shift 写出的版本表达相同的核心过程:把比 key 大的元素向右移动,最终把 key 放到空出来的位置。

逐步示例

以 increasing order 排序:

text
初始:       5  2  4  6  1  3
插入 2:     2  5  4  6  1  3
插入 4:     2  4  5  6  1  3
插入 6:     2  4  5  6  1  3
插入 1:     1  2  4  5  6  3
插入 3:     1  2  3  4  5  6

每一轮中,key 向右移动一个位置;如果 prefix 已经 sorted,algorithm 只需要把 key 向左移动到正确位置。例如插入 1 时,它需要越过 6、5、4、2,因此需要四次移动或等价的 swaps。

Correctness invariant

外层 loop 的 invariant 是:在开始第 i 轮时,A[0 ... i-1] 已 sorted,并且包含原数组中前 i 个 items。内层 loop 每次把一个大于 key 的元素向右移,保持 prefix 中其余元素的相对顺序;loop 结束时,key 左侧不大于它,右侧不小于它。因此第 i 轮结束后,A[0 ... i] sorted。最后一轮结束,整个 array sorted。

Complexity

外层 loop 有 Θ(n) 轮。每一轮最多移动 Θ(n) 个 elements;reverse-sorted input 会触发最坏情况。因此:

text
comparisons:Θ(n²)
swaps/moves:Θ(n²)
worst-case time:Θ(n²)

如果输入已经 sorted,内层 loop 几乎不做 work,best-case 可以达到 Θ(n)。当比较 numbers 时,通常把 compare 和 swap 视为相近成本;但如果 elements 是 records,comparison function 可能很昂贵,而 swap 只需交换 references。分析时要明确到底在数 comparisons、swaps,还是两者总和。

Binary insertion sort

因为 A[0 ... i-1] 已经 sorted,可以对它做 binary search,寻找 A[i] 应该插入的位置。每轮 comparisons 从线性下降到 Θ(log i),总 comparisons 为:

text
Σ(i=1..n) Θ(log i) = Θ(n log n)

但对于 array data structure,找到位置后仍需把中间 elements 向右移动;最坏情况下每轮移动 Θ(n) 个 elements。因此:

text
binary insertion sort comparisons:Θ(n log n)
swaps/moves:Θ(n²)

这说明降低 comparisons 并不自动降低整体 running time;data movement 也可能成为 bottleneck。

Merge sort

Divide and conquer

merge sort 把 array A 分成两个 halves L 和 R,递归地把两半分别排序,然后用 merge 把两个 sorted arrays 合并成一个 sorted array:

text
Merge-Sort(A):
    if |A| ≤ 1:
        return A
    split A into L and R
    L′ ← Merge-Sort(L)
    R′ ← Merge-Sort(R)
    return Merge(L′, R′)

递归 split 本身几乎不做排序工作;主要工作集中在 merge routine。merge 的 invariant 是:它的两个 inputs L′ 和 R′ 已经 sorted。

Two-finger merge

假设两个 sorted arrays 为:

text
L′ = [2, 7, 13, 20]
R′ = [1, 9, 11, 12]

在每个 array 的开头放置一个 pointer(two fingers),比较两个 pointers 指向的 elements,把较小者写入 output,然后只移动对应 pointer:

text
比较 2 与 1 → 输出 1
比较 2 与 9 → 输出 2
比较 7 与 9 → 输出 7
继续比较并输出较小者
最终输出 [1, 2, 7, 9, 11, 12, 13, 20]
text
Merge(L, R):
    result ← []
    i ← 0
    j ← 0
    while i < |L| and j < |R|:
        if L[i] ≤ R[j]:
            append L[i] to result
            i ← i + 1
        else:
            append R[j] to result
            j ← j + 1
    append remaining elements of L or R to result
    return result

每一步至少消耗一个 input element,两个 inputs 总共 n 个 elements,因此 merge 的 work 是 Θ(n)。

Merge sort recurrence

输入规模为 n 时,两个递归子问题各为 n/2,merge 需要 cn work:

text
T(n) = 2T(n/2) + cn

Recursion tree

展开 T(n)=2T(n/2)+cn:

text
level 0:                 cn
level 1:             cn/2   cn/2
level 2:          cn/4 cn/4 cn/4 cn/4
   ...
leaves:              c  c  ...  c       (n 个 leaves)

树的 height 是 log₂ n + 1,leaves 数量是 n。每一层的总 work 都约为 cn:

text
level 0: cn
level 1: 2 · c(n/2) = cn
level 2: 4 · c(n/4) = cn

因此:

text
T(n) = cn · (1 + log₂ n)
     = Θ(n log n)

空间、常数与实际性能

In-place 与 auxiliary space

insertion sort 只需要 swap 时的一个 temporary variable,auxiliary space 为 Θ(1),因此是 in-place sorting algorithm。

普通 merge sort 需要把 L 和 R 的递归结果复制到 L′ 和 R′,再写回 A,因此 auxiliary space 为 Θ(n)。对于 billion 或 trillion 个 elements,额外 storage 可能成为重要约束。

可以通过 coding trick 把额外 storage 的常数因子从 n 降到约 n/2;也存在理论上的 in-place merge sort,仍为 Θ(n log n),但 constant factors 和 implementation complexity 较高,实际通常不如使用 Θ(n) auxiliary space 的标准 merge sort。

Asymptotic complexity 与 constant factors

讲义给出一组旧机器上的数量级测量:

text
Python merge sort:     约 2.2 n log n 微秒
Python insertion sort: 约 0.2 n² 微秒
C insertion sort:      约 0.01 n² 微秒

C 的常数因子可能比 Python 好约 20 倍,但 n² 的增长最终会压过这个优势。讲义估计,当 n 超过约 4,000 时,Python merge sort 也可能超过 C insertion sort。这说明 constant factors 在小输入上重要,而 asymptotic complexity 决定规模继续增长后的趋势。

其他 recurrence 的递归树

如果 merge step 错误地需要 cn²,递推式为:

text
T(n) = 2T(n/2) + cn²

每层总工作依次约为 cn²、cn²/2、cn²/4、...,root 层已经支配总和,因此 T(n)=Θ(n²)。

如果 merge step 只需要 constant work:

text
T(n) = 2T(n/2) + c

每层工作依次为 c、2c、4c、...、nc,leaves 层支配总和,因此 T(n)=Θ(n)。

递归树提供一个直观判断:每层 work 大致相同,结果通常是 Θ(n log n);root 支配时接近 root work;leaves 支配时接近 leaves work。

小结

insertion sort 通过维护 sorted prefix 获得简单的 in-place 实现,但 array 中的逐项移动使其 worst-case 为 Θ(n²);binary search 只能降低 comparisons,不能消除 shifts。merge sort 把问题分成两个 halves,用 Θ(n) 的 two-finger merge 组合结果,并通过 recursion tree 得到 Θ(n log n)。算法选择必须同时考虑 asymptotic time、comparisons、data movement、auxiliary space 和 constant factors。

参考资料

← 返回列表
← 上一篇 Models of Computation:RAM、Python Cost Model 与 Document Distance 下一篇 → Heap:优先队列、建堆与 Heap Sort

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论