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

Heap:优先队列、建堆与 Heap Sort

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

Algorithms:Heaps and Heap Sort

本文逐段翻译 MIT 6.006 Fall 2011 Lecture 4《Heaps and Heap Sort》,从 priority queue 出发说明 heap 的 array/tree 表示、max-heap property、max-heapify、build-max-heap 与 heap sort,并重点分析为什么 build-max-heap 是 Θ(n) 而不是表面上的 Θ(n log n)。

TL;DR

  • Heap 的用途:heap 是 priority queue 的一种实现,支持 insert、max/min、extract max/min 和 priority update。
  • 表示方式:同一个 array 被视为 nearly complete binary tree;对 1-based index,parent 是 ⌊i/2⌋,children 是 2i 与 2i+1。
  • Invariant:max-heap 要求每个 node 的 key 不小于 children 的 keys;root 因而是 maximum。
  • 核心操作:max-heapify 只修复一个 violation,沿树高向下运行 O(log n);从 leaves 向 root 调用它可以在线性时间 build heap。
  • Heap sort:build heap 后反复把 root 与末尾交换、缩小 heap、重新 heapify,得到 in-place 的 Θ(n log n) sorting algorithm。

目录

章节说明
Lecture 4:Heaps and Priority Queuespriority queue 的操作规范
Heap 的 array/tree 表示index 映射与 nearly complete tree
Max-heap propertyrepresentation invariant
max-heapify修复单个 violation
build-max-heap从无序 array 构建 max-heap
Heap sortextract max 与排序
复杂度总结Θ(n)、Θ(log n) 与 Θ(n log n)

Lecture 4:Heaps and Priority Queues

heap 是一种很小巧的 data structure,既可以实现 priority queue,也可以用来构造 heap sort。priority queue 表示一个带有 keys 的 set S,常见操作包括:

text
insert(S, x)              把 element x 加入 S
max(S)                    返回 key 最大的 element
extract-max(S)            返回并删除 key 最大的 element
increase-key(S, x, k)     把 x 的 key 增加到 k

也可以定义 min-oriented version,例如 min、extract-min 和 decrease-key。这些操作的“快”通常用 asymptotic complexity 描述:O(1)、O(log n) 或 O(n)。

heap 的关键不是任意 array,而是维护一个 representation invariant,使 priority queue 的操作能够高效执行。

Heap 的 array/tree 表示

heap 是一个 array,但我们把它可视化为 nearly complete binary tree。比如有 10 个 elements 时,array 可以表示成:

text
array index:  1   2   3   4   5   6   7   8   9   10
tree level:   root      level 1        level 2 ...

它不是 full binary tree,因为最后一层不一定填满;但 nodes 从左到右连续排列,因此 tree height 为 Θ(log n)。

对于 1-based indexing:

text
parent(i) = floor(i / 2)
left(i)   = 2i
right(i)  = 2i + 1

例如 array:

text
A = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]

root 是 A[1] = 16;A[2] 与 A[3] 是它的 children;A[4]、A[5]、A[6]、A[7] 是下一层;最后一层继续从左向右填充。

Max-heap property

max-heap property 要求每个 node 的 key 大于或等于它的 children 的 keys:

text
key(parent) ≥ key(child)

这个条件必须对 tree 中每个 node 成立。leaves 没有 children,因此自动满足 property。min-heap property 只需把关系反过来:

text
key(parent) ≤ key(child)

在 max-heap 中,root 必然是 maximum,因此 max(S) 可以直接读取 root,且不会破坏 invariant。extract-max 则更复杂:删除 root 后必须重新建立 max-heap property。

需要区分“把 array 看成 heap”和“array 是 max-heap”。任意 array 都能被可视化成 nearly complete tree,但只有满足 parent/child key relationship 的 array 才是 max-heap;它可能既不是 max-heap,也不是 min-heap。

max-heapify

Contract 与 precondition

max-heapify(A, i) 的作用是修复以 i 为 root 的 subtree 中的单个 max-heap violation。它的 precondition 是:left(i) 和 right(i) 各自已经是 max-heaps;唯一可能的问题是 A[i] 小于某个 child。

text
Max-Heapify(A, i):
    l ← left(i)
    r ← right(i)
    largest ← i

    if l ≤ heap-size(A) and A[l] > A[largest]:
        largest ← l
    if r ≤ heap-size(A) and A[r] > A[largest]:
        largest ← r

    if largest ≠ i:
        exchange A[i] with A[largest]
        Max-Heapify(A, largest)

algorithm 比较两个 children,选择 key 较大的 child 与当前 node exchange。交换后,原来的 violation 可能沿着较大的 child 继续向下;但因为两个 child subtrees 原本是 max-heaps,新的 violation 只有这一条路径。

示例

考虑局部结构:

text
        4
      /   \
    14     7
   /  \
  8    3

max-heapify(A, i) 发现 14 大于 4,先交换:

text
        14
      /    \
     4      7
   /  \
  8    3

此时 violation 移到 4 所在的位置;继续与 child 8 交换:

text
        14
      /    \
     8      7
   /  \
  4    3

如果到达 leaf,过程结束。

Complexity

max-heapify 每层只做 constant work,最多沿着一条 root-to-leaf path 下行。nearly complete binary tree 的 height 为 Θ(log n),所以:

text
max-heapify:O(log n)

这里的 precondition 很重要。如果两个 child subtrees 也可能包含任意多 violations,algorithm 就不能只沿一条路径修复,复杂度和 correctness argument 都会改变。

build-max-heap

从 leaves 向 root

任意 unordered array 都可以先转换成 max-heap。关键观察是:array 中从 ⌊n/2⌋ + 1 到 n 的 elements 都是 leaves,它们天然是 max-heaps。因此可以从最后一个 internal node 向 root 倒序调用 max-heapify:

text
Build-Max-Heap(A):
    heap-size(A) ← length(A)
    for i ← floor(length(A) / 2) downto 1:
        Max-Heapify(A, i)

为什么每次调用都满足 precondition?从底层开始时,children 是 leaves,已经是 max-heaps;修复一个 internal node 后,它就成为 max-heap,随后更高一层的 node 就可以把它作为已经修复的 child subtree。

为什么不是 Θ(n log n)

粗略分析会说有约 n/2 次调用,每次最多 O(log n),得到 O(n log n)。这是有效的 upper bound,但不够精确,因为不同 nodes 的 height 不同:

  • leaves 不调用 heapify;
  • 离 leaves 一层的约 n/4 个 nodes,最多只下行 1 层;
  • 离 leaves 两层的约 n/8 个 nodes,最多下行 2 层;
  • 越接近 root,nodes 越少,但单个 node 的 work 越大。

总 work 可以写成:

text
W(n) ≤ (n/4) · 1c
     + (n/8) · 2c
     + (n/16) · 3c
     + ...
     + 1 · (log n)c

令 n/4 = 2^k,提取 c · 2^k 后,剩下类似:

text
1/2^0 + 2/2^1 + 3/2^2 + ... + (k+1)/2^k

这是一个有界的 convergent series,因此总 work 是 O(2^k)=O(n)。同时,构建过程至少需要接触线性数量的 array elements,因此得到:

text
Build-Max-Heap:Θ(n)

这说明同一个 algorithm 的复杂度分析可能因是否认真计算每一层的 nodes 数量而不同;O(n log n) 是松的 upper bound,准确结果是 Θ(n)。

Heap sort

有了 Build-Max-Heap 后,可以反复取出 maximum。为了原地完成 sorting,不必实现一个单独的 extract-max container:把 root 与当前 heap 的最后一个 element exchange,把 maximum 放到 sorted suffix,然后减小 heap-size,再对新的 root 调用 max-heapify。

text
Heap-Sort(A):
    Build-Max-Heap(A)
    for i ← length(A) downto 2:
        exchange A[1] with A[i]
        heap-size(A) ← heap-size(A) - 1
        Max-Heapify(A, 1)

每次 exchange 后,A[i] 已经是当前 heap 的 maximum,并且不再属于 heap。新的 root 可能违反 max-heap property,但 root 的 children subtrees 仍然是 max-heaps,所以 max-heapify 的 precondition 成立。

例如 max-heap [4, 2, 1]:

text
exchange root and last: [1, 2 | 4]
heap-size = 2
heapify:                 [2, 1 | 4]
再次取出 2:              [1, 2, 4]

竖线右侧是已经排好序的 suffix;heap 区域逐步缩小,最终 array ascending sorted。

Complexity 与空间

Build-Max-Heap 需要 Θ(n);循环有 n-1 次,每次 max-heapify 为 O(log n),因此:

text
Heap-Sort:Θ(n) + Θ(n log n) = Θ(n log n)

heap sort 的额外 space 主要是 exchange 所需的 temporary variable,因此为 Θ(1) auxiliary space,是 in-place sorting algorithm。它同时具有 Θ(n log n) worst-case bound;相比 insertion sort,它避免了二次增长;相比标准 merge sort,它不需要 Θ(n) auxiliary array。

复杂度总结

操作复杂度关键原因
maxΘ(1)maximum 在 root
max-heapifyO(log n)沿 tree height 的单一路径下行
build-max-heapΘ(n)大多数 nodes 离 leaves 很近,按高度加权求和
heap-sortΘ(n log n)n 次 heapify,每次 O(log n)
auxiliary spaceΘ(1)array 内交换与 heap-size 管理

小结

heap 用 nearly complete binary tree 的结构约束 array,并用 max-heap property 让 root 代表 maximum。max-heapify 利用“只有一条 violation、两个 child subtrees 已正确”的 precondition,在 O(log n) 内修复局部结构;从 leaves 向上调用它时,必须按每层 nodes 数量和高度仔细分析,才能得到 build-max-heap 的 Θ(n)。最后,heap sort 通过不断把 root 移到 sorted suffix,获得 in-place、worst-case Θ(n log n) 的 sorting algorithm。

参考资料

← 返回列表
← 上一篇 Sorting:Insertion Sort、Merge Sort 与递推树分析 下一篇 → BST:插入、查询与 Rank 的增广设计

评论 (0)

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