e01.org

Heapsort

In computer science, heapsort is an efficient, comparison-based sorting algorithm that reorganizes an input array into a heap (a data structure where each node is greater than its children) and then repeatedly removes the largest node from that heap, placing it at the end of the array in a similar manner to Selection sort. Although somewhat slower in practice on most machines than a well-implemented quicksort, it has the advantages of very simple implementation and a more favorable worst-case runtime. Most real-world quicksort variants include an implementation of heapsort as a fallback should they detect that quicksort is becoming degenerate. Heapsort is an in-place algorithm, but it is not a stable sort. Heapsort was invented by J. W. J. Williams in 1964. The paper also introduced the binary heap as a useful data structure in its own right. In the same year, Robert W. Floyd published an improved version that could sort an array in-place, continuing his earlier research into the...

In computer science, heapsort is an efficient, comparison-based sorting algorithm that reorganizes an input array into a heap (a data structure where each node is greater than its children) and then repeatedly removes the largest node from that heap, placing it at the end of the array in a similar manner to Selection sort. Although somewhat slower in practice on most machines than a well-implemented quicksort, it has the advantages of very simple implementation and a more favorable worst-case runtime. Most real-world quicksort variants include an implementation of heapsort as a fallback should they detect that quicksort is becoming degenerate. Heapsort is an in-place algorithm, but it is not a stable sort. Heapsort was invented by J. W. J. Williams in 1964. The paper also introduced the binary heap as a useful data structure in its own right. In the same year, Robert W. Floyd published an improved version that could sort an array in-place, continuing his earlier research into the treesort algorithm. iLeftChild(i) = 2⋅i + 1 iRightChild(i) = 2⋅i + 2 iParent(i) = floor((i−1) / 2) where the floor function rounds down to the preceding integer. For a more detailed explanation, see . This binary tree is a max-heap when each node is greater than or equal to both of its children. Equivalently, each node is less than or equal to its parent. This rule, applied throughout the tree, results in the maximum node being located at the root of the tree. In the first phase, a heap is built out of the data (see ). In the second phase, the heap is converted to a sorted array by repeatedly removing the largest element from the heap (the root of the heap), and placing it at the start of the sorted array. The heap is updated after each removal to maintain the heap property. Once all objects have been removed from the heap, the result is a sorted array. Heapsort is normally performed in place. During the first phase, the array is divided into an unsorted prefix and a heap-ordered suffix (initially empty). Each step shrinks the prefix and expands the suffix. When the prefix is empty, this phase is complete. During the second phase, the array is divided into a heap-ordered prefix and a sorted suffix (initially empty). Each step shrinks the prefix and expands the suffix. When the prefix is empty, the array is sorted. parent := iParent(end) if a[parent] 2 = 9 elements, doing more work with six comparisons than three levels in the binary heap, which only cover 2 3 = 8. This is primarily of academic interest, or as a student exercise, as the additional complexity is not worth the minor savings, and bottom-up heapsort beats both. Memory-optimized heapsort improves heapsort's locality of reference by increasing the number of children even more. This increases the number of comparisons, but because all children are stored consecutively in memory, reduces the number of cache lines accessed during heap traversal, a net performance improvement. The standard implementation of Floyd's heap-construction algorithm causes a large number of cache misses once the size of the data exceeds that of the CPU cache. Better performance on large data sets can be obtained by merging in depth-first order, combining subheaps as soon as possible, rather than combining all subheaps on one level before proceeding to the one above. Out-of-place heapsort improves on bottom-up heapsort by eliminating the worst case, guaranteeing comparisons. When the maximum is taken, rather than fill the vacated space with an unsorted data value, fill it with a sentinel value, which never "bounces" back up. It turns out that this can be used as a primitive in an in-place (and non-recursive) "QuickHeapsort" algorithm. First, you perform a quicksort-like partitioning pass, but reversing the order of the partitioned data in the array. Suppose (without loss of generality) that the smaller partition is the one greater than the pivot, which should go at the end of the array, but our reversed partitioning step places it at the beginning. Form a heap out of the smaller partition and do out-of-place heapsort on it, exchanging the extracted maxima with values from the end of the array. These are less than the pivot, meaning less than any value in the heap, so serve as sentinel values. Once the heapsort is complete (and the pivot moved to just before the now-sorted end of the array), the order of the partitions has been reversed, and the larger partition at the beginning of the array may be sorted in the same way. (Because there is no non-tail recursion, this also eliminates quicksort's stack usage.) The smoothsort algorithm is a variation of heapsort developed by Edsger W. Dijkstra in 1981. Like heapsort, smoothsort's upper bound is . The advantage of smoothsort is that it comes closer to time if the input is already sorted to some degree, whereas heapsort averages regardless of the initial sorted state. Due to its complexity, smoothsort is rarely used. Levcopoulos and Petersson describe a variation of heapsort based on a heap of Cartesian trees. First, a Cartesian tree is built from the input in time, and its root is placed in a 1-element binary heap. Then we repeatedly extract the minimum from the binary heap, output the tree's root element, and add its left and right children (if any) which are themselves Cartesian trees, to the binary heap. As they show, if the input is already nearly sorted, the Cartesian trees will be very unbalanced, with few nodes having left and right children, resulting in the binary heap remaining small, and allowing the algorithm to sort more quickly than for inputs that are already nearly sorted. Several variants such as weak heapsort require comparisons in the worst case, close to the theoretical minimum, using one extra bit of state per node. While this extra bit makes the algorithms not truly in-place, if space for it can be found inside the element, these algorithms are simple and efficient, but still slower than binary heaps if key comparisons are cheap enough (e.g. integer keys) that a constant factor does not matter. Katajainen's "ultimate heapsort" requires no extra storage, performs comparisons, and a similar number of element moves. It is, however, even more complex and not justified unless comparisons are very expensive.

References

  1. ^ Bollobás, B.; Fenner, T. I.; Frieze, A. M. (1996). "On the Best Case of Heapsort" (PDF) . Journal of Algorithms . 20 (11): 205– 217. doi : 10.1006/jagm.1996.0011 . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  2. ^ Knuth, Donald E. (1973). Sorting and Searching . The Art of Computer Programming . Vol. 3 (1st ed.). Reading, MA: Addison-Wesley Professional. Ex. 18, p. 158, § 5.2.3. ISBN 0-201-03803-X . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  3. ^ Moret, Bernard ; Shapiro, Henry D. (1991). "8.6 Heapsort". Algorithms from P to NP Volume 1: Design and Efficiency . Benjamin/Cummings. p. 528. ISBN 0-8053-8008-6 . For lack of a better name we call this enhanced program 'heapsort with bounce. ' Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  4. ^ Wegener, Ingo (March 1992). "The worst-case complexity of McDiarmid and Reed's variant of Bottom-Up Heapsort is less than n log n + 1.1 n " . Information and Computation . 97 (1): 86– 96. doi : 10.1016/0890-5401(92)90005-Z . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  5. ^ Tenenbaum, Aaron M.; Augenstein, Moshe J. (1981). "Chapter 8: Sorting". Data Structures Using Pascal . Prentice-Hall. p. 405. ISBN 0-13-196501-8 . Write a sorting routine similar to the heapsort except that it uses a ternary heap. Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  6. ^ Sedgewick, Robert ; Schaffer, Russel W. (October 1990). The Best Case of Heapsort (Technical report). Princeton University. TR-293-90. Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  7. ^ Chen, Jingsen; Edelkamp, Stefan; Elmasry, Amr; Katajainen, Jyrki (27–31 August 2012). "In-place Heap Construction with Optimized Comparisons, Moves, and Cache Misses" ( (PDF) ) . Mathematical Foundations of Computer Science 2012 . 37th international conference on Mathematical Foundations of Computer Science. Lecture Notes in Computer Science. Vol. 7464. pp. 259– 270. doi : 10.1007/978-3-642-32589-2_25 . ISBN 978-3-642-32588-5 . S2CID 1462216 . Archived from the original on 29 December 2016. See particularly Fig. 3. Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  8. ^ Cantone, Domenico; Concotti, Gianluca (1–3 March 2000). QuickHeapsort, an efficient mix of classical sorting algorithms . 4th Italian Conference on Algorithms and Complexity. Lecture Notes in Computer Science. Vol. 1767. Rome. pp. 150– 162. ISBN 3-540-67159-5 . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  9. ^ Cantone, Domenico; Concotti, Gianluca (August 2002). "QuickHeapsort, an efficient mix of classical sorting algorithms" (PDF) . Theoretical Computer Science . 285 (1): 25– 42. doi : 10.1016/S0304-3975(01)00288-2 . Zbl 1016.68042 . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  10. ^ Diekert, Volker; Weiß, Armin (August 2016). "QuickHeapsort: Modifications and improved analysis". Theory of Computing Systems . 59 (2): 209– 230. arXiv : 1209.4214 . doi : 10.1007/s00224-015-9656-y . S2CID 792585 . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  11. ^ Dijkstra, Edsger W. Smoothsort – an alternative to sorting in situ (EWD-796a) (PDF) . E.W. Dijkstra Archive. Center for American History, University of Texas at Austin . ( transcription ) Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  12. ^ Levcopoulos, Christos; Petersson, Ola (1989). "Heapsort—Adapted for Presorted Files". WADS '89: Proceedings of the Workshop on Algorithms and Data Structures . Lecture Notes in Computer Science. Vol. 382. London, UK: Springer-Verlag. pp. 499– 509. doi : 10.1007/3-540-51542-9_41 . ISBN 978-3-540-51542-5 . Heapsort—Adapted for presorted files (Q56049336) . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  13. ^ Schwartz, Keith (27 December 2010). "CartesianTreeSort.hh" . Archive of Interesting Code . Retrieved 5 March 2019 . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  14. ^ Katajainen, Jyrki (2–3 February 1998). The Ultimate Heapsort . Computing: the 4th Australasian Theory Symposium. Australian Computer Science Communications . Vol. 20, no. 3. Perth. pp. 87– 96. Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  15. ^ Cormen, Thomas H.; Leiserson, Charles Eric; Rivest, Ronald L.; Stein, Clifford (2022). Introduction to algorithms (4th ed.). Cambridge, Massachusetts: The MIT Press. p. 170. ISBN 978-0-262-04630-5 . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  16. ^ Peters, Orson R. L. (9 June 2021). "Pattern-defeating Quicksort". arXiv : 2106.05123 [ cs.DS ]. Peters, Orson R. L. "pdqsort" . Github . Retrieved 2 October 2023 . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  17. ^ Morris, John (1998). "Comparing Quick and Heap Sorts" . Data Structures and Algorithms (Lecture notes). University of Western Australia . Retrieved 12 February 2021 . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  18. ^ https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/lib/sort.c#n205 Linux kernel source Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  19. ^ Maus, Arne [in Norwegian] (14 May 2014). "Sorting by generating the sorting permutation, and the effect of caching on sorting" . See Fig. 1 on p. 6. Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  20. ^ Edelkamp, Stefan; Weiß, Armin (30 January 2019). "BlockQuicksort: Avoiding Branch Mispredictions in Quicksort" (PDF) . Journal of Experimental Algorithmics . 24 1.4. arXiv : 1604.06697 . doi : 10.1145/3274660 . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  21. ^ Aumüller, Martin; Hass, Nikolaj (7–8 January 2019). Simple and Fast BlockQuicksort using Lomuto's Partitioning Scheme . Twenty-First Workshop on Algorithm Engineering and Experiments (ALENEX). San Diego. arXiv : 1810.12047 . doi : 10.1137/1.9781611975499.2 . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  22. ^ Williams 1964 Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  23. ^ Suchenek, Marek A. (2012). "Elementary Yet Precise Worst-Case Analysis of Floyd's Heap-Construction Program". Fundamenta Informaticae . 120 (1): 75– 92. doi : 10.3233/FI-2012-751 . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  24. ^ Suchenek, Marek A. (7 April 2015). "A Complete Worst-Case Analysis of Heapsort with Experimental Verification of Its Results, A manuscript". arXiv : 1504.01459 [ cs.DS ]. Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  25. ^ Knuth 1997 Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  26. ^ a b c Bojesen, Jesper; Katajainen, Jyrki; Spork, Maz (2000). "Performance Engineering Case Study: Heap Construction" (PostScript) . ACM Journal of Experimental Algorithmics . 5 (15): 15–es. doi : 10.1145/351827.384257 . S2CID 30995934 . Alternate PDF source . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  27. ^ a b Carlsson, Scante (March 1987). "A variant of heapsort with almost optimal number of comparisons" (PDF) . Information Processing Letters . 24 (4): 247– 250. doi : 10.1016/0020-0190(87)90142-6 . S2CID 28135103 . Archived from the original (PDF) on 27 December 2016. Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  28. ^ Katajainen, Jyrki (23 September 2013). Seeking for the best priority queue: Lessons learnt . Algorithm Engineering (Seminar 13391). Dagstuhl. pp. 19– 20, 24. Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  29. ^ a b c LaMarca, Anthony; Ladner, Richard E. (April 1999). "The Influence of Caches on the Performance of Sorting" (PDF) . Journal of Algorithms . 31 (1): 66– 104. doi : 10.1006/jagm.1998.0985 . S2CID 206567217 . See particularly figure 9c on p. 98. Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  30. ^ a b MacKay, David J. C. (December 2005). "Heapsort, Quicksort, and Entropy" . Retrieved 12 February 2021 . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  31. ^ a b McDiarmid, C. J. H.; Reed, B. A. (September 1989). "Building heaps fast" (PDF) . Journal of Algorithms . 10 (3): 352– 365. doi : 10.1016/0196-6774(89)90033-3 . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  32. ^ a b Mehlhorn, Kurt ; Sanders, Peter (2008). "Priority Queues" (PDF) . Algorithms and Data Structures: The Basic Toolbox . Springer. p. 142. ISBN 978-3-540-77977-3 . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  33. ^ a b c Wegener, Ingo (13 September 1993). "Bottom-Up Heapsort, a new variant of Heapsort beating, on an average, Quicksort (if n is not very small)" (PDF) . Theoretical Computer Science . 118 (1): 81– 98. doi : 10.1016/0304-3975(93)90364-y . Although this is a reprint of work first published in 1990 (at the Mathematical Foundations of Computer Science conference), the technique was published by Carlsson in 1987. [ 17 ] Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  34. ^ a b Brass, Peter (2008). Advanced Data Structures . Cambridge University Press. p. 209. ISBN 978-0-521-88037-4 . Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  35. ^ a b c Fleischer, Rudolf (February 1994). "A tight lower bound for the worst case of Bottom-Up-Heapsort" (PDF) . Algorithmica . 11 (2): 104– 115. doi : 10.1007/bf01182770 . hdl : 11858/00-001M-0000-0014-7B02-C . S2CID 21075180 . Archived from the original (PDF) on 14 June 2018 . Retrieved 14 June 2018 . Also available as Fleischer, Rudolf (April 1991). A tight lower bound for the worst case of Bottom-Up-Heapsort (PDF) (Technical report). MPI-INF . MPI-I-91-104. Wikipedia revision 1373708813, retrieved 2026-11-22 · 1795302000.0
  36. Bollobás, B. On the Best Case of Heapsort . 1996. · 1788735600.0
  37. Chen, Jingsen. web.archive.org . (archived copy) · 1788735600.0
  38. Cantone, Domenico. QuickHeapsort, an efficient mix of classical sorting algorithms . · 1788735600.0
  39. Schwartz, Keith. CartesianTreeSort.hh . Archive of Interesting Code . 27 December 201. · 1788735600.0
  40. Katajainen, Jyrki. Seeking for the best priority queue: Lessons learnt . 23 September 2013. · 1788735600.0
  41. Katajainen, Jyrki. The Ultimate Heapsort . 2–3 February 1998. · 1788735600.0
  42. Peters, Orson R. L. Pattern-defeating Quicksort . 9 Jun 2021. · 1788735600.0
  43. Morris, John. Comparing Quick and Heap Sorts . Data Structures and Algorithms . 1998. · 1788735600.0
  44. https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/lib/sort.c#n205 Linux kernel source . · 1788735600.0
  45. LaMarca, Anthony. The Influence of Caches on the Performance of Sorting . · 1788735600.0
  46. Maus, Arne. Sorting by generating the sorting permutation, and the effect of caching on sorting . 14 May 2014. · 1788735600.0
  47. Sedgewick, Robert. The Best Case of Heapsort . · 1788735600.0
  48. Edelkamp, Stefan. BlockQuicksort: Avoiding Branch Mispredictions in Quicksort . · 1788735600.0
  49. MacKay, David J. C. Heapsort, Quicksort, and Entropy . December 2005. · 1788735600.0
  50. Fleischer, Rudolf. A tight lower bound for the worst case of Bottom-Up-Heapsort . February 1994. · 1788735600.0
  51. procedure siftDown(a, i, end) is j ← leafSearch(a, i, end) while a[i] > a[j] do j ← iParent(j) while j > i do swap(a[i], a[j]) j ← iParent(j) Bottom-up heapsort was . · 1788735600.0
  52. Carlsson, Scante. A variant of heapsort with almost optimal number of comparisons . Marc. · 1788735600.0
  53. Building heaps fast . · 1788735600.0
  54. Bojesen, Jesper. Performance Engineering Case Study: Heap Construction . · 1788735600.0
  55. Chen, Jingsen. pdfs.semanticscholar.org . · 1788735600.0
source: e01 Encyclopedia · licence: CC BY-SA 4.0 · page · source revision

Cite this

"Heapsort". 1788781453. e01 Encyclopedia. CC BY-SA 4.0. https://en.wikipedia.org/w/index.php?oldid=1373708813

JSON record · API collection · BibTeX · RIS · CSL-JSON · citation policy

Save to pass ·