{"id":188,"date":"2026-11-13T12:33:59","date_gmt":"2026-11-13T04:33:59","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-heapsort-sorts-in-place-in-n-log-n\/"},"modified":"2026-11-13T21:52:08","modified_gmt":"2026-11-13T13:52:08","slug":"how-heapsort-sorts-in-place-in-n-log-n","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-heapsort-sorts-in-place-in-n-log-n\/","title":{"rendered":"How heapsort sorts in place in n log n"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Heapsort<\/strong> turns the array into a binary max-heap, then repeatedly swaps the root with the last unsorted item and sifts the hole down. Building the heap is <strong>\u0398(n)<\/strong>. The n extractions are <strong>\u0398(n log n)<\/strong> in the worst case. Extra memory is a few indices. The sort pays for an in-place worst-case bound with more scattered reads than quicksort and with an unstable result.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">A binary heap stores a parent at index i and its children at 2i+1 and 2i+2, in the same array. The heap property says every parent is at least its children. The maximum is then at index 0 and can be moved to the end of the unsorted prefix in one swap. The remaining problem is to restore the heap property on a prefix one item shorter.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The build phase has a tighter bound than n times an insertion. A bottom-up pass sifts short subheaps first. Most nodes are leaves or sit near the leaves, so the total sift during construction is linear.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Floyd&#8217;s heapify, from the last parent at index floor(n\/2)\u22121 down to the root, runs in \u0398(n) comparisons. Each of the n\u22121 extractions sifts a root down a tree of height floor(log\u2082 of the current size), so the sort is \u0398(n log n) comparisons in the worst case and cannot do better than that lower bound in the comparison model by more than a constant. Extra memory is O(1).<\/p>\n\n\n<p class=\"wp-block-paragraph\">The result is unstable: sifting swaps equal keys according to their positions in the tree. Cache behavior is weaker than quicksort&#8217;s sequential partition, because each sift jumps to a child at twice the index. Those jumps are the practical reason a library may still prefer a hybrid quicksort when a worst-case proof is arranged another way.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Index the array from 0. The parent of i is floor((i\u22121)\/2). The children of i are 2i+1 and 2i+2.<\/li>\n<li>Sift down from index floor(n\/2)\u22121 through 0. Sift down swaps a node with its larger child until the parent is at least both children or a leaf is reached.<\/li>\n<li>The array is now a max-heap. The maximum sits at index 0.<\/li>\n<li>For end from n\u22121 down to 1, swap index 0 with end, and sift down on the prefix of length end.<\/li>\n<li>The swapped value at end is in its final place. When the prefix has length 1, the array is sorted ascending.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The bound is for a random-access array that can host an implicit heap. A stable sort, a nearly sorted adaptive sort, or an external file is outside it. The linear build does not make the whole sort linear. The extractions dominate.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when an in-place n log n sort is required<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Insert n keys into an empty heap, one by one, and call the build linear<\/td>\n<td>n insertions cost \u0398(n log n). The linear bound is the bottom-up sift from the last parent.<\/td>\n<\/tr>\n<tr>\n<td>Sift up during the bottom-up build<\/td>\n<td>Sift up repairs one leaf-to-root path per node and reintroduces an n log n build. The construction sift moves the hole downward.<\/td>\n<\/tr>\n<tr>\n<td>Stop after the heap exists<\/td>\n<td>A heap is only partially ordered. The parent rule fixes the root. The sorted array is produced by the extractions.<\/td>\n<\/tr>\n<tr>\n<td>Expect equal keys to keep their order<\/td>\n<td>A sift compares positions in the tree and swaps those records. Equals move.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">A stable n log n sort with a linear buffer is mergesort. An in-place sort with a better typical constant, and a heap used only as a backstop, is introsort.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The Bash script and the Python script heapsort in place. Children of index i are 2i+1 and 2i+2. Both print <code>1 2 3 4 5<\/code>.<\/p>\n\n<pre><code class=\"language-bash\">a=(3 1 4 5 2)\nn=${#a[@]}\nsift() {\n  local i=$1 end=$2 left right best t\n  while :; do\n    left=$((2*i+1)); right=$((2*i+2)); best=$i\n    if (( left &lt; end &amp;&amp; a[left] &gt; a[best] )); then best=$left; fi\n    if (( right &lt; end &amp;&amp; a[right] &gt; a[best] )); then best=$right; fi\n    if (( best == i )); then return; fi\n    t=${a[i]}; a[i]=${a[best]}; a[best]=$t\n    i=$best\n  done\n}\nfor ((i=n\/2-1; i&gt;=0; i--)); do sift &quot;$i&quot; &quot;$n&quot;; done\nfor ((end=n-1; end&gt;0; end--)); do\n  t=${a[0]}; a[0]=${a[end]}; a[end]=$t\n  sift 0 &quot;$end&quot;\ndone\necho &quot;${a[*]}&quot;\n<\/code><\/pre>\n<pre><code class=\"language-python\">def heapsort(a):\n    n = len(a)\n\n    def sift(i, end):\n        while True:\n            left, right = 2 * i + 1, 2 * i + 2\n            best = i\n            if left &lt; end and a[left] &gt; a[best]:\n                best = left\n            if right &lt; end and a[right] &gt; a[best]:\n                best = right\n            if best == i:\n                return\n            a[i], a[best] = a[best], a[i]\n            i = best\n\n    for i in range(n \/\/ 2 - 1, -1, -1):\n        sift(i, n)\n    for end in range(n - 1, 0, -1):\n        a[0], a[end] = a[end], a[0]\n        sift(0, end)\n    return a\n\na = heapsort([3, 1, 4, 5, 2])\nassert a == [1, 2, 3, 4, 5]\nprint(*a)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Heapsort is the in-place fallback inside <strong>introsort<\/strong>, the algorithm of C++ <code>std::sort<\/code>, once recursion gets too deep. The Linux kernel&#8217;s in-place sort is a heapsort as well. A stable sort such as timsort is what a caller needs when equal keys must keep their order.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop heapsort when stability is required, or when the array is usually small and nearly sorted. Insertion sort and timsort win those inputs. Keep heapsort when the worst case must be n log n, the extra buffer must be constant, and scattered child reads are acceptable.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for heapsort returns the linear heapify and the n log n extractions as separate phases. <strong>Heapsort builds a heap in linear time and then extracts the maximum n times, for an in-place worst case of n log n comparisons.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: Heapsort turns the array into a binary max-heap, then repeatedly swaps the root with the last unsorted item and sifts the hole down. Building the heap is \u0398(n). The n extractions are \u0398(n log n) in the worst case. Extra memory is a few indices. The sort&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,31],"tags":[],"class_list":["post-188","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-sorting"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/188","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=188"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/188\/revisions"}],"predecessor-version":[{"id":587,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/188\/revisions\/587"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=188"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=188"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=188"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}