# 堆排序

**堆排序**是一种基于比较的[排序算法](https://www.edgepedia.org/zh/sorting-algorithm)，它首先把输入数组组织成二叉堆——一种存储在数组内部的完全二叉树——然后反复从根取出剩余最大元素来构建有序输出。J. W. J. 威廉姆斯（J. W. J. Williams）于1964年在《ACM通讯》（*Communications of the ACM*）上以“算法232：堆排序”（Algorithm 232: Heapsort）为题提出该方法，同年晚些时候[罗伯特·W·弗洛伊德](https://www.edgepedia.org/zh/robert-w-floyd)（Robert W. Floyd）给出了高效的自底向上建堆模式。<sup>[1](https://hjemmesider.diku.dk/~henglein/bib/publications/williams1964.html)</sup><sup> • </sup><sup>[2](https://xlinux.nist.gov/dads/HTML/treesort2.html)</sup>

| 关键事实 | 详情 |
|---|---|
| 起源 | 威廉姆斯，“算法232：堆排序”，《ACM通讯》7(6):347–348，1964；弗洛伊德的“算法245：树排序3”（Algorithm 245: Treesort 3，1964）给出了高效构造<sup>[1](https://hjemmesider.diku.dk/~henglein/bib/publications/williams1964.html)</sup><sup> • </sup><sup>[2](https://xlinux.nist.gov/dads/HTML/treesort2.html)</sup> |
| 时间 | 建堆为 O(n)，随后 n 次取出每次 Θ(log n)，最坏情况下总计 Θ(n log n)<sup>[3](https://www.robots.ox.ac.uk/~vedaldi/assets/teach/2023/b16/notes/5-heaps.html)</sup> |
| 空间 | 原地排序，额外内存 O(1)，因为“树”就是被排序的数组<sup>[4](https://distillcourse.com/courses/algorithms-and-data-structures/lessons/heapsort-and-the-sorting-lower-bound)</sup> |
| 稳定性 | 不稳定；相等元素可能改变相对顺序<sup>[5](https://www.ime.usp.br/~pf/algorithms/chapters/heapsort.html)</sup> |
| 实际作用 | 内省排序（introsort）背后的最坏情况保证，而内省排序是 C++ `std::sort` 的常用实现<sup>[6](https://en.cppreference.com/cpp/algorithm/sort)</sup> |
| 弱点 | 缓存局部性差；尽管堆排序的最坏情况更好，快速排序在实践中通常更快<sup>[7](https://www.sciencedirect.com/science/article/pii/S0196677498909853)</sup><sup> • </sup><sup>[8](https://www.eecs.umich.edu/courses/eecs380/ALG/qsort3.html)</sup> |

## 堆排序所用的堆

堆排序所使用的堆形式，是把一个数组视为一棵完全二叉树，其中每个父节点持有的值都大于或等于其子节点的值（最大堆；最小堆则反转比较）。<sup>[5](https://www.ime.usp.br/~pf/algorithms/chapters/heapsort.html)</sup><sup> • </sup><sup>[9](https://koclab.cs.ucsb.edu/teaching/cs130a/docx/06-chapHeapsort.pdf)</sup> 这种有序性刻意弱于二叉搜索树：它只要求父子之间的支配关系，而不要求左右子树之间的完整排序，这正是该结构维护成本低的原因。<sup>[10](https://www.codehistory.org/algorithms-data-structures-computational-complexity/williams-floyd-heap-heapsort-history/)</sup> 由于树是完全的，不需要指针；数组中某个位置的父节点和子节点可由下标运算得出，因此输入数组同时充当数据集和树。<sup>[10](https://www.codehistory.org/algorithms-data-structures-computational-complexity/williams-floyd-heap-heapsort-history/)</sup>

核心维护操作把一个值从根向下移动，与较大的子节点交换，直到它稳定下来；对于含 m 个元素的堆，这至多花费约 \( 2\,\lg(m) \) 次比较，与树高成正比。<sup>[5](https://www.ime.usp.br/~pf/algorithms/chapters/heapsort.html)</sup> 对于完全树，高度与 \( \log n \) 成正比，因此一次这样的操作是 \( \Theta(\log n) \)。<sup>[3](https://www.robots.ox.ac.uk/~vedaldi/assets/teach/2023/b16/notes/5-heaps.html)</sup>

## 算法

对数组 A 进行堆排序分两个阶段：<sup>[3](https://www.robots.ox.ac.uk/~vedaldi/assets/teach/2023/b16/notes/5-heaps.html)</sup>

1. **建堆。** 原地重排 A，使其满足堆性质。弗洛伊德的自底向上构造对每个内部子树调用下滤操作，内部子树共有 \( \lfloor n/2 \rfloor \) 个。<sup>[3](https://www.robots.ox.ac.uk/~vedaldi/assets/teach/2023/b16/notes/5-heaps.html)</sup><sup> • </sup><sup>[10](https://www.codehistory.org/algorithms-data-structures-computational-complexity/williams-floyd-heap-heapsort-history/)</sup>
2. **反复取出。** 对于 \( i = |A|-1, \dots, 1 \)：交换根 \( A_0 \) 与 \( A_i \)，这会把剩余最大元素放到数组末尾的最终有序位置，然后在不断缩小的子数组 \( (A_0, \dots, A_{i-1}) \) 内下滤以恢复堆。<sup>[3](https://www.robots.ox.ac.uk/~vedaldi/assets/teach/2023/b16/notes/5-heaps.html)</sup>

因为最大元素位于根处，取出的元素会从数组末尾向开头反向填入有序数组，且不需要辅助存储。<sup>[3](https://www.robots.ox.ac.uk/~vedaldi/assets/teach/2023/b16/notes/5-heaps.html)</sup><sup> • </sup><sup>[11](https://mexicodev.org/en/dsa-course/heapsort/index.html)</sup>

## 复杂度

**线性时间构造。** 对建堆的朴素上界是 O(n log n)，因为它最多执行 \( \lfloor n/2 \rfloor \) 次下滤。真实成本更低，因为大多数子树都很短：对于高度为 h 的满树，总工作量为 \( \sum_{i=0}^{h} i\,2^{h-i} = 2^{h+1} - h - 2 \)，约为 \( 2n - \log_2 n - 2 \)，即 O(n)。<sup>[3](https://www.robots.ox.ac.uk/~vedaldi/assets/teach/2023/b16/notes/5-heaps.html)</sup>

**总体上界。** 取出阶段执行 n 次下滤，其成本合计为 \( \Theta(n \log n) \)，因此堆排序的最坏情况总成本为 \( \Theta(n \log n) \)，与基于比较的排序的下界相符。<sup>[3](https://www.robots.ox.ac.uk/~vedaldi/assets/teach/2023/b16/notes/5-heaps.html)</sup> 即使把线性时间的堆化替换为 n 次单独插入，也不会改变总体 O(n log n) 复杂度。<sup>[12](https://web.engr.oregonstate.edu/~huanlian/algorithms_course/1-datastructures/heap_apps.html)</sup>

**精确的最坏情况比较次数。** 一项完整分析表明，对于任意大小为 \( N \geq 2 \) 的数组，最坏情况下的比较次数等于 \( 2(N-1)\,(\,\lg \frac{N-1}{2} + \varepsilon \,) - 2s_2(N) - e_2(N) + \min(\lfloor \lg (N-1) \rfloor, 2) + 6 + c \)，其中 \( \varepsilon \) 是 N 的函数，最小值为 0，上确界为 \( \delta = 1 - \lg e + \lg \lg e \approx 0.0860713320559342 \)，\( s_2(N) \) 是 N 的二进制数字之和，\( e_2(N) \) 是 N 的质因数分解中 2 的指数，且当 \( N \leq 2^{\lceil \lg N \rceil} - 4 \) 时 c 为 1，否则为 0。<sup>[13](https://arxiv.org/abs/1504.01459)</sup>

## 实践中的堆排序

**缓存行为。** 堆排序的弱点是内存访问模式：下滤操作在相距很远的数组位置之间跳转，导致缓存局部性差，而且该算法对于可放入缓存的实例也并不特别快。<sup>[7](https://www.sciencedirect.com/science/article/pii/S0196677498909853)</sup><sup> • </sup><sup>[14](https://arxiv.org/abs/1811.00833)</sup> 实证研究表明，快速排序通常明显更快，大多数商业应用因其更好的平均性能而偏好快速排序。<sup>[8](https://www.eecs.umich.edu/courses/eecs380/ALG/qsort3.html)</sup> 重构归并排序、快速排序和堆排序以改善缓存局部性，会降低这三者的总执行时间。<sup>[7](https://www.sciencedirect.com/science/article/pii/S0196677498909853)</sup>

**内省排序的保证。** 堆排序的价值在于其最坏情况上界与原地操作的结合，而这是快速排序所缺乏的，因为快速排序可能退化到二次时间。<sup>[4](https://distillcourse.com/courses/algorithms-and-data-structures/lessons/heapsort-and-the-sorting-lower-bound)</sup> 内省排序利用这一点：它运行快速排序，统计递归深度，并在超过 \( 2 \lg n \) 层后把有问题的子数组切换为堆排序，从而以 O(N log N) 次比较处理所有情况，且在平均情况下没有额外开销；它是 C++ `std::sort` 的常用实现。<sup>[4](https://distillcourse.com/courses/algorithms-and-data-structures/lessons/heapsort-and-the-sorting-lower-bound)</sup><sup> • </sup><sup>[6](https://en.cppreference.com/cpp/algorithm/sort)</sup>

**变体与近亲。** 弗洛伊德的树排序算法被认为是通向如今所谓堆排序的发展。<sup>[2](https://xlinux.nist.gov/dads/HTML/treesort2.html)</sup> 混合设计以它为基础：快速堆排序（QuickHeapsort）原地工作，其平均运行时间曾与最高效的快速排序和堆排序变体进行比较研究，<sup>[15](https://www.sciencedirect.com/science/article/pii/S0304397501002882)</sup> 而原地自底向上堆排序（Bottom-Up-Heapsort）被推测平均最多使用 \( n \lg n + 0.4n \) 次比较，使用 n 个额外位的弱堆排序（Weak-Heapsort）则以 \( n \lg n - 0.42n \) 为界。<sup>[16](https://arxiv.org/abs/1209.4214)</sup>

## 与优先队列的关系

堆排序是堆的另一主要用途——优先队列——的排序对应物；在优先队列中，顶部元素可以在 O(log N) 时间内取出或插入。<sup>[17](https://webdocs.cs.ualberta.ca/~holte/T26/heap-uses.html)</sup> 用优先队列排序，就是插入所有项，然后按顺序取出它们；堆排序是这一思想的原地版本，而堆最初正是由此获得动机：堆化花费 O(n)，n 次弹出花费 O(n log n)。<sup>[12](https://web.engr.oregonstate.edu/~huanlian/algorithms_course/1-datastructures/heap_apps.html)</sup> 这种联系比类比更深：k 路归并排序使用一个堆合并 k 个有序子列表，在极端 \( k = n \) 时恰好退化为堆排序，而经典归并排序是 \( k = 2 \) 时的另一极端。<sup>[12](https://web.engr.oregonstate.edu/~huanlian/algorithms_course/1-datastructures/heap_apps.html)</sup>

## References

1. [J. W. J. Williams. Algorithm 232 – Heapsort. Communications of the ACM 7(6):347–348, 1964.](https://hjemmesider.diku.dk/~henglein/bib/publications/williams1964.html)
2. [treesort (2), NIST Dictionary of Algorithms and Data Structures](https://xlinux.nist.gov/dads/HTML/treesort2.html)
3. [Chapter 5 Heaps, B16 Algorithms and Data Structures 1 Notes, University of Oxford](https://www.robots.ox.ac.uk/~vedaldi/assets/teach/2023/b16/notes/5-heaps.html)
4. [Heapsort and the comparison-sort lower bound, distillcourse](https://distillcourse.com/courses/algorithms-and-data-structures/lessons/heapsort-and-the-sorting-lower-bound)
5. [Heapsort algorithm: correctness and performance analysis, IME-USP](https://www.ime.usp.br/~pf/algorithms/chapters/heapsort.html)
6. [std::sort, cppreference.com](https://en.cppreference.com/cpp/algorithm/sort)
7. [The Influence of Caches on the Performance of Sorting, Journal of Algorithms 31(1):66–104, 1999](https://www.sciencedirect.com/science/article/pii/S0196677498909853)
8. [Data Structures and Algorithms: Quick vs Heap Sort, University of Michigan](https://www.eecs.umich.edu/courses/eecs380/ALG/qsort3.html)
9. [Introduction to Algorithms, Third Edition, Chapter 6: Heapsort](https://koclab.cs.ucsb.edu/teaching/cs130a/docx/06-chapHeapsort.pdf)
10. [J. W. J. Williams, Robert Floyd, and the Heap Behind Heapsort, CodeHistory](https://www.codehistory.org/algorithms-data-structures-computational-complexity/williams-floyd-heap-heapsort-history/)
11. [Heapsort, Data Structures & Algorithms From Scratch](https://mexicodev.org/en/dsa-course/heapsort/index.html)
12. [1.7 Applications of Heap, Oregon State University](https://web.engr.oregonstate.edu/~huanlian/algorithms_course/1-datastructures/heap_apps.html)
13. [A Complete Worst-Case Analysis of Heapsort with Experimental Verification of Its Results, arXiv:1504.01459](https://arxiv.org/abs/1504.01459)
14. [Worst-Case Efficient Sorting with QuickMergesort, arXiv:1811.00833](https://arxiv.org/abs/1811.00833)
15. [QuickHeapsort, an efficient mix of classical sorting algorithms, Theoretical Computer Science](https://www.sciencedirect.com/science/article/pii/S0304397501002882)
16. [QuickHeapsort: Modifications and improved analysis, arXiv:1209.4214](https://arxiv.org/abs/1209.4214)
17. [Lecture 10: Uses of Heaps, University of Alberta](https://webdocs.cs.ualberta.ca/~holte/T26/heap-uses.html)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 30, 2026; Oct 15, 2026 · Edited: Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 人工智能与数据 › Algorithms and computational methods › Sorting, searching, and selection › Comparison sorting algorithms

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/heapsort

English original: https://www.edgepedia.org/heapsort
