# 原地算法

原地算法是一种除输入之外只使用常数空间的算法；在算法工程中，有时只要额外空间与输入规模成对数，人们就感到满意。<sup>[1](https://dl.acm.org/doi/fullHtml/10.1145/3505286)</sup> 在排序中，该术语把[堆排序](https://www.edgepedia.org/zh/heapsort)和[快速排序](https://www.edgepedia.org/zh/quicksort)这类在原存储中重排数组的算法，与标准归并排序这类在合并阶段需要辅助数组的算法区分开来。<sup>[2](https://www.uni-koblenz.de/de/mathematik-naturwissenschaften/mathe/personen/personenverzeichnis/lehrbeauftragte/willems/lehre/heapscormen-pdf/@@download/file)</sup><sup> • </sup><sup>[3](http://opendatastructures.org/newhtml/ods/latex/sorting.html)</sup>

| 关键事实 | 细节 |
|---|---|
| 严格定义 | 在算法理论中，原地算法只使用常数额外空间；此情形使用“严格原地”一词，而算法工程常常接受对数额外空间。<sup>[1](https://dl.acm.org/doi/fullHtml/10.1145/3505286)</sup> |
| 典型例子 | 堆排序原地排序，在任意时刻只在输入数组之外存储常数个数组元素，时间为 O(n lg n)。<sup>[2](https://www.uni-koblenz.de/de/mathematik-naturwissenschaften/mathe/personen/personenverzeichnis/lehrbeauftragte/willems/lehre/heapscormen-pdf/@@download/file)</sup> |
| 快速排序的注意事项 | 对较小子问题递归、对较大子问题迭代的快速排序需要递归栈的对数额外空间；如果两个子问题都递归处理，糟糕的枢轴规则可能使递归深度增长到 n。<sup>[1](https://dl.acm.org/doi/fullHtml/10.1145/3505286)</sup><sup> • </sup><sup>[4](https://www.algorithms-data-structures.com/essays/in-place-is-a-claim/)</sup> |
| 实测空间 | 在一次测量中，堆排序、希尔排序和插入排序使用 1 个辅助槽位；三数取中快速排序在随机输入上使用 22 个槽位；归并排序使用 4,110 个槽位。<sup>[4](https://www.algorithms-data-structures.com/essays/in-place-is-a-claim/)</sup> |
| 开放问题 | 是否存在具有 O(n log n) 次比较和 O(n) 次移动的稳定原地排序仍属开放问题；已知最好的、具有 O(n) 次移动的稳定原地算法执行 O(n^(1+ε)) 次比较。<sup>[5](https://dl.acm.org/doi/10.1145/1082036.1082037)</sup> |
| 实际速度 | IPS4o 并行原地排序的速度接近此前最好的原地并行基于比较的排序算法的三倍，部分原因是原地工作避免了输入数组之外的显著空间。<sup>[1](https://dl.acm.org/doi/fullHtml/10.1145/3505286)</sup> |

## 定义与形式刻画

**三种定义在流传。** 根据算法理论，当一个顺序算法在输入之外的额外内存以常数为界时，它就是原地运行；工程文献将这种情况称为*严格原地*，尽管有时它接受随输入规模对数增长的额外空间。<sup>[1](https://dl.acm.org/doi/fullHtml/10.1145/3505286)</sup> 第三种常见解读将“原地”简单视为运行期间不进行分配。<sup>[4](https://www.algorithms-data-structures.com/essays/in-place-is-a-claim/)</sup> 这些定义选出不同的算法集合：快速排序在 O(log n) 和无分配两种解读下是原地的，但不是严格原地，因为其递归栈深度等于划分树的深度。<sup>[4](https://www.algorithms-data-structures.com/essays/in-place-is-a-claim/)</sup>

分歧有实践根源。O(log n) 个指针的栈，如快速排序的递归栈或 Timsort 与 [Powersort](https://www.edgepedia.org/zh/powersort) 的运行段栈，内存占用可忽略不计，并且常常实现为静态固定大小数组，因此许多作者接受它为“原地”，尽管严格说来原地应意味着完全没有额外内存。<sup>[6](https://drops.dagstuhl.de/storage/00lipics/lipics-vol388-esa2026/LIPIcs.ESA.2026.14/LIPIcs.ESA.2026.14.pdf)</sup>

形式模型使这些变化明确化。有些论文用“原地”仅指对数空间计算（FL），而另一些论文允许在写访问输入之外再有一个只写输出带。inplaceFL 模型要求在单条读写带上以仅 O(log n) 的额外工作空间将输入 x 变换为 f(x)，而 Restore 模型仅当输入修改在运行结束时被还原时才允许修改输入。<sup>[7](https://iuuk.mff.cuni.cz/~iwmertz/papers/cgmps25.structure_of_in_place_computation.pdf)</sup> 这种输入之外 O(1) 的约定也适用于排序之外：当一个优先队列在数组前部保存 n 个元素之外只占用 O(1) 额外空间时，它就算作原地运行。<sup>[8](https://kclpure.kcl.ac.uk/ws/files/87388857/TheoryComputingSzstems.pdf)</sup>

## 原地算法如何工作

原地算法覆写其输入而不破坏仍需要的数据，方法是始终让每个值可达，通常通过少数几种机制之一。基本操作是交换：两个元素使用一个额外元素存储位置交换位置，算法携带至少 lg n 位的 O(1) 个辅助字，用于数组下标、循环计数器和指针。<sup>[9](https://arxiv.org/abs/2607.27040v1)</sup>

**簿记替代内存。** 快速排序围绕枢轴划分数组并递归；先递归较小子问题可将栈限制为对数深度，而严格原地变体通过从左到右处理数组并谨慎放置枢轴来完全避免递归。<sup>[1](https://dl.acm.org/doi/fullHtml/10.1145/3505286)</sup> 堆排序在结构上达到同样效果：它把数组本身当作二叉堆，因此数据结构位于输入内部，任意时刻只有常数个元素位于其外。<sup>[2](https://www.uni-koblenz.de/de/mathematik-naturwissenschaften/mathe/personen/personenverzeichnis/lehrbeauftragte/willems/lehre/heapscormen-pdf/@@download/file)</sup>

## 典型例子

**堆排序**是教科书式的原地排序：像插入排序而不像归并排序，它原地排序；与插入排序不同，它运行时间为 O(n lg n)。<sup>[2](https://www.uni-koblenz.de/de/mathematik-naturwissenschaften/mathe/personen/personenverzeichnis/lehrbeauftragte/willems/lehre/heapscormen-pdf/@@download/file)</sup> 在相同空间内可以改进其比较次数：自底向上堆排序的 1.5 n log n 比较上界是紧的，而卡尔松（Carlsson）的堆排序变体需要 n log n + Θ(n log log n) 次比较，麦克迪尔米德（McDiarmid）与里德（Reed）的变体则是首个具有 n log n + O(n) 次比较的近原地算法。<sup>[10](https://users.informatik.uni-halle.de/~ahyjb/sort.pdf)</sup>

**快速排序**是原地的，并且以这种方式实现时通常是通用选项中最快的，但它不稳定。<sup>[6](https://drops.dagstuhl.de/storage/00lipics/lipics-vol388-esa2026/LIPIcs.ESA.2026.14/LIPIcs.ESA.2026.14.pdf)</sup> GCC 的 C++ 标准库使用了一种带堆排序回退的快速排序变体，以避免最坏情况。<sup>[1](https://dl.acm.org/doi/fullHtml/10.1145/3505286)</sup>

**原地归并排序变体**以比较换空间。黄（Huang）与兰斯顿（Langston）1988 年的原地归并排序变体具有 3n log n 次比较的上界。<sup>[10](https://users.informatik.uni-halle.de/~ahyjb/sort.pdf)</sup> 实用原地归并排序表现不佳：对于大输入，WikiSort 的用时超过 QuickMergesort 的 1.5 倍，GrailSort 的表现与 WikiSort 类似，而近期一项工程综述未发现实用的并行原地归并排序实现。<sup>[1](https://dl.acm.org/doi/fullHtml/10.1145/3505286)</sup>

原地优先队列也已被开发出来：一种提出的二叉堆变体原地工作，以 O(1) 最坏情况运行时间执行取最小值与插入操作，以 O(lg n) 最坏情况运行时间执行提取最小值，同时元素间比较不超过 lg n + O(1) 次。<sup>[8](https://kclpure.kcl.ac.uk/ws/files/87388857/TheoryComputingSzstems.pdf)</sup>

## 数据一览

实测峰值辅助空间显示经典排序在实践中的表现差异有多大。在一次带插桩的比较中，堆排序、[希尔排序](https://www.edgepedia.org/zh/shellsort)和插入排序各使用 1 个辅助槽位；三数取中快速排序在随机输入上使用 22 个槽位，在有序输入上使用 14 个槽位；采用首元素枢轴的快速排序在 4,096 个元素的有序输入上达到 4,097 个槽位；归并排序使用 4,110 个槽位。<sup>[4](https://www.algorithms-data-structures.com/essays/in-place-is-a-claim/)</sup> 快速排序的递归深度取决于枢轴规则和输入：枢轴规则糟糕时，递归深度会增长到 n，可能导致栈溢出失败。<sup>[4](https://www.algorithms-data-structures.com/essays/in-place-is-a-claim/)</sup>

**规模化基准测试。** IPS4o 与 IPS2Ra 背后的工程研究覆盖 21 个排序代码、6 种数据类型、10 种输入分布、4 台机器、4 种内存分配策略，以及跨越 7 个数量级的输入规模；在近均匀分布、小键或串行运行等许多其余情形中，IPS2Ra 表现最佳。<sup>[1](https://dl.acm.org/doi/fullHtml/10.1145/3505286)</sup> IPS4o 的分块原地数据分布使用不依赖输入大小的块大小，并且可证明具有缓存高效性。<sup>[1](https://dl.acm.org/doi/fullHtml/10.1145/3505286)</sup>

原地属性并不自动意味着牺牲速度，但它可能如此。一种可用约 150 行 C 代码实现的原地美国国旗（基数）排序，在奔腾（Pentium）上排序 100 万到 1000 万个 32 位数字时，用时约为使用额外内存的基数排序的 2.5 倍，但略快于快速排序。<sup>[11](https://people.csail.mit.edu/mip/papers/radix/arxiv.pdf)</sup> 相反，重构归并排序、快速排序和堆排序以改善缓存局部性，会降低这三者的总执行时间；而基数排序尽管指令数少且时间为线性，缓存性能却相对较差，最终比高效的基于比较的排序更慢。<sup>[12](https://www.cs.auckland.ac.nz/~mcw/Teaching/refs/sorting/ladner-lamarca-cach-sorting.pdf)</sup>

## 尚不能原地完成的事

核心开放问题是具有最少数据移动的稳定原地排序。已知最好的、具有 O(n) 次移动的稳定原地排序算法在最坏情况下执行 O(n^(1+ε)) 次比较；是否存在具有 O(n log n) 次比较和 O(n) 次移动的稳定原地排序仍属开放问题。<sup>[5](https://dl.acm.org/doi/10.1145/1082036.1082037)</sup> 所有已知的最少移动原地排序算法都不稳定。<sup>[9](https://arxiv.org/abs/2607.27040v1)</sup>

确实存在一种具有常数额外空间和线性次数据移动的稳定排序，已知构造需要二次时间；对于具有 k 个不同值且 k 为常数的输入，稳定原位算法可以进行 O(n lg^(k+1) n + kn) 次比较和 O(kn) 次移动。<sup>[13](https://link.springer.com/article/10.1007/BF02017344)</sup> 更广泛地说，像归并排序、归并-插入排序或插入排序这样比较高效的方法，要么需要 O(n^2) 次搬移，要么使用需要 2n 个位置的数据结构；这正是经典时空权衡，原地变体以比较为代价摆脱它。<sup>[10](https://users.informatik.uni-halle.de/~ahyjb/sort.pdf)</sup>

## 原地与非原地

同时稳定且辅助空间为 O(1) 的[比较排序](https://www.edgepedia.org/zh/comparison-sort)是块归并构造，其代码可达数百行且常数很大；堆排序、快速排序和希尔排序都不稳定。<sup>[4](https://www.algorithms-data-structures.com/essays/in-place-is-a-claim/)</sup> 相比之下，归并排序很容易实现为稳定方法，且不依赖随机化，但它在合并阶段使用一个辅助数组；分配该数组可能代价高昂，并且在内存有限时是潜在故障点。<sup>[6](https://drops.dagstuhl.de/storage/00lipics/lipics-vol388-esa2026/LIPIcs.ESA.2026.14/LIPIcs.ESA.2026.14.pdf)</sup><sup> • </sup><sup>[3](http://opendatastructures.org/newhtml/ods/latex/sorting.html)</sup> C++ 的 std::stable_sort 明确体现了这种权衡：它尝试获得大小为 n 的缓冲区，如果无法获得，则退化为 O(n log^2 n) 次比较。<sup>[4](https://www.algorithms-data-structures.com/essays/in-place-is-a-claim/)</sup>

**并行性使选择复杂化。** 在并行原地（PIP）模型中，一种宽松原地过滤算法以 O(n) 工作量、O(n log n) 跨度和 O(n^(1-ε)) 辅助空间将未过滤元素移到数组前部；并行原地算法必须同时平衡工作量、跨度和较小辅助空间。<sup>[14](https://jshun.csail.mit.edu/PIP.pdf)</sup> 性能图景是混合的而非单方面的：历史上，原地特性常常意味着性能惩罚，但 IPS4o 的速度优势部分源于原地工作而无需输入数组之外的显著空间。<sup>[1](https://dl.acm.org/doi/fullHtml/10.1145/3505286)</sup>

## 实践中的原地计算

除排序库之外，原地技术出现在内存或写入耐久度稀缺的任何地方。嵌入式计算机系统内存有限，这促使人们采用仅使用 O(1) 额外内存的严格原地算法；在嵌入式非易失性主存中，如果内存被多次覆写，例如不得不维护栈这样的数据结构，内存会退化。<sup>[15](https://arxiv.org/abs/2603.05676v1)</sup>

**数据库**有选择地使用原地更新。PostgreSQL 的 heap_inplace_update 将新元组数据直接复制到缓冲页中现有元组之上，要求新元组的总长度和头部偏移与旧元组完全相同；它为崩溃恢复生成 XLOG_HEAP_INPLACE WAL 记录，不更新索引，并且设计用于元组大小保持不变的系统目录更新。<sup>[16](https://ryogrid.github.io/create_pg_super_document/h/heap_inplace_update_and_unlock.html)</sup> 在闪存存储上，原地追加（IPA）技术将小型数据库更新转化为更新增量，追加到同一物理闪存页上的保留区域，从而避免异地写入；在更新密集型负载下，它实现了页面失效减少 67%、垃圾回收开销降低 80%、事务吞吐量提高 45%、闪存寿命翻倍，并比页内日志（In-Page Logging）高出 50% 以上。<sup>[17](https://doi.org/10.5441/002/edbt.2017.76)</sup>

**函数式语言**面临相反约束，因为其数据结构通常是不可变的。FP2（全原地函数式编程）系列工作展示了包括伸展树在内的函数式数据结构如何能够完全原地使用。<sup>[18](https://www.microsoft.com/en-us/research/wp-content/uploads/2023/05/fbip.pdf)</sup>

## 近期进展

近期工作收紧了已知边界。一项 2026 年的结果将原地最少移动排序的上界改进为 n lg n + O(n lg^(t) n) 次比较和 O(tn) 次数据移动，其中 t 是满足 2 ≤ t ≤ lg* n − 1 的整数参数，lg^(t) n 表示 t 次迭代对数。<sup>[9](https://arxiv.org/abs/2607.27040v1)</sup> 在实践方面，2026 年的工作提供了首批严格原地、并且在输入基于运行段的熵 H(A) 意义上最优的基于比较的排序算法，通过两种简单的基于栈的自然归并排序范式在 O(n(1 + H(A))) 时间内运行。<sup>[15](https://arxiv.org/abs/2603.05676v1)</sup> 一项 2025 年关于原地空间有界计算结构的综述统一了模型图景，其观察包括：在 O(n log n) 时间内使用 O(log n) 额外空间原地排序一个含 n 个 O(log n) 位整数的数组是可能的——正如堆排序所展示的那样——并且近期并行原地研究将“原地”视为意味着 polylog(n) 或 n^(1-ε) 空间开销，同时对于二次幂长度有可用的原地快速傅里叶变换。<sup>[7](https://iuuk.mff.cuni.cz/~iwmertz/papers/cgmps25.structure_of_in_place_computation.pdf)</sup>

## References

1. [Engineering In-place (Shared-memory) Sorting Algorithms, ACM](https://dl.acm.org/doi/fullHtml/10.1145/3505286)
2. [Introduction to Algorithms, Third Edition (Cormen et al.), heapsort chapter](https://www.uni-koblenz.de/de/mathematik-naturwissenschaften/mathe/personen/personenverzeichnis/lehrbeauftragte/willems/lehre/heapscormen-pdf/@@download/file)
3. [Open Data Structures, Sorting Algorithms chapter](http://opendatastructures.org/newhtml/ods/latex/sorting.html)
4. [In place is a claim, and it is usually wrong about quicksort](https://www.algorithms-data-structures.com/essays/in-place-is-a-claim/)
5. [An in-place sorting with O(n log n) comparisons and O(n) moves, Journal of the ACM](https://dl.acm.org/doi/10.1145/1082036.1082037)
6. [Virtual-Memory Powersort, ESA 2026, LIPIcs](https://drops.dagstuhl.de/storage/00lipics/lipics-vol388-esa2026/LIPIcs.ESA.2026.14/LIPIcs.ESA.2026.14.pdf)
7. [The Structure of In-Place Space-Bounded Computation (2025)](https://iuuk.mff.cuni.cz/~iwmertz/papers/cgmps25.structure_of_in_place_computation.pdf)
8. [In-place priority queues, King's College London](https://kclpure.kcl.ac.uk/ws/files/87388857/TheoryComputingSzstems.pdf)
9. [Upper Bounds for In-Place Sorting with Minimal Moves, arXiv (2026)](https://arxiv.org/abs/2607.27040v1)
10. [Sorting with n log n − 1.3n + O(log n) Comparisons and ε n log n + O(1) Transports](https://users.informatik.uni-halle.de/~ahyjb/sort.pdf)
11. [In-place American flag sort (radix sort) practical experience](https://people.csail.mit.edu/mip/papers/radix/arxiv.pdf)
12. [The Influence of Caches on the Performance of Sorting (Ladner & LaMarca)](https://www.cs.auckland.ac.nz/~mcw/Teaching/refs/sorting/ladner-lamarca-cach-sorting.pdf)
13. [Stable in situ sorting and minimum data movement, BIT Numerical Mathematics](https://link.springer.com/article/10.1007/BF02017344)
14. [Parallel In-Place Algorithms: Theory and Practice, MIT CSAIL](https://jshun.csail.mit.edu/PIP.pdf)
15. [How to Sort in a Refrigerator: Simple Entropy-Sensitive Strictly In-Place Sorting Algorithms, arXiv (2026)](https://arxiv.org/abs/2603.05676v1)
16. [heap_inplace_update_and_unlock, PostgreSQL symbol documentation](https://ryogrid.github.io/create_pg_super_document/h/heap_inplace_update_and_unlock.html)
17. [In-Place Appends for Real: DBMS Overwrites on Flash without Erase](https://doi.org/10.5441/002/edbt.2017.76)
18. [FP2: Fully in-Place Functional Programming, Microsoft Research](https://www.microsoft.com/en-us/research/wp-content/uploads/2023/05/fbip.pdf)

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

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

Copyright 2026 Edgepedia

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

Source: https://www.edgepedia.org/zh/in-place-algorithm

English original: https://www.edgepedia.org/in-place-algorithm
