{"id":257,"date":"2026-11-13T12:36:07","date_gmt":"2026-11-13T04:36:07","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-smoothsort-adapts-a-heap-to-sorted-input\/"},"modified":"2026-11-13T21:53:51","modified_gmt":"2026-11-13T13:53:51","slug":"how-smoothsort-adapts-a-heap-to-sorted-input","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-smoothsort-adapts-a-heap-to-sorted-input\/","title":{"rendered":"How smoothsort adapts a heap to sorted input"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Smoothsort<\/strong> keeps the unsorted prefix as a forest of implicit heaps whose sizes are <strong>Leonardo numbers<\/strong>, then peels maxima from the right. Sorted input costs <strong>\u0398(n)<\/strong>. Every input costs <strong>O(n log n)<\/strong>. The sort is in place and unstable. Dijkstra designed it so a heap sort would become cheap exactly when the array was already in order.<\/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\">Heapsort pays n log n even on a sorted array, because the heap construction and the extractions do not become trivial when the array is ordered. An adaptive heap has to grow by appending one item, keep the maximum at a known place, and do only constant work per item when the new item is already the next maximum.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Leonardo numbers supply the heap sizes. They obey L(0) = 1, L(1) = 1, and L(k) = L(k\u22121) + L(k\u22122) + 1. A heap of size L(k) is a root whose two children are heaps of sizes L(k\u22121) and L(k\u22122), laid out immediately to its left. That layout lives inside the array.<\/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\">The forest represents the unsorted prefix as Leonardo heaps, largest on the left, with the roots ordered so the rightmost root is the maximum of the forest. Appending an item either opens a new heap or combines the two rightmost heaps with the new root into the next Leonardo size, then sifts. On a nondecreasing array the sift and the later extraction do amortized constant work per item, which is the \u0398(n) case. A disordered array pays the full heap cost, O(n log n). Extra memory is O(1) plus a constant-size description of the forest shape.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The sort is unstable. Heap order compares keys and swaps records that are not neighbors in the input. The practical constants are larger than heapsort&#8217;s, so the adaptive case is the reason to consider the algorithm at all.<\/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>Grow the forest from left to right. Each new item extends the Leonardo shape: combine the two rightmost heaps when their sizes are consecutive Leonardo numbers that form the next size, otherwise start a heap of size 1.<\/li>\n<li>Store a heap of size L(k) as a heap of size L(k\u22121), then a heap of size L(k\u22122), then the root.<\/li>\n<li>Sift a new root so each Leonardo heap is a heap and the sequence of roots has its maximum at the rightmost root.<\/li>\n<li>To emit the next sorted item from the end, remove the rightmost root. It is the maximum of the remaining prefix. Split its two child heaps back into the forest and sift the roots again.<\/li>\n<li>Repeat the extraction until the forest is empty. The emitted suffix is sorted.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The linear case is sorted, or more generally input that is already close to the order in which maxima are peeled. It is not a stable adaptive sort. Timsort takes that contract and also uses natural runs that are not heap-shaped. Smoothsort&#8217;s advantage over heapsort disappears on random data, where both are n log n and heapsort has the smaller constant.<\/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 a sorted array must become a linear heap sort<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Ordinary heapsort<\/td>\n<td>Build and extract are \u0398(n log n) on a sorted array. The Leonardo forest is what collapses that case to linear.<\/td>\n<\/tr>\n<tr>\n<td>Any forest of fixed-size heaps<\/td>\n<td>The sizes have to follow the recurrence so that two child heaps plus a root make the next legal heap. Arbitrary sizes break the in-place layout.<\/td>\n<\/tr>\n<tr>\n<td>Expect timsort&#8217;s constants on nearly sorted objects<\/td>\n<td>Smoothsort&#8217;s siftes jump through the Leonardo layout. A library that needs stability and speed on runs uses timsort.<\/td>\n<\/tr>\n<tr>\n<td>Call the algorithm stable because sorted input is barely moved<\/td>\n<td>Disordered equal keys are still swapped by siftes. Stability is not part of the result.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">A stable adaptive sort belongs to timsort. A simpler in-place n log n sort, with a worse sorted-input case, belongs to heapsort.<\/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\">This Python fragment grows Leonardo heaps, keeps each heap a max-heap, and keeps the roots in nondecreasing order so the rightmost root is the next output. The permutation 3, 1, 4, 2 sorts as <code>1 2 3 4<\/code>.<\/p>\n\n<pre><code class=\"language-python\">def smoothsort(values):\n    leo = [1, 1]\n    while leo[-1] &lt; len(values) + 2:\n        leo.append(leo[-1] + leo[-2] + 1)\n\n    def sift(i, k):\n        while k &gt; 1:\n            left = i - leo[k - 2] - 1\n            right = i - 1\n            child, ck = (left, k - 1) if values[left] &gt; values[right] else (right, k - 2)\n            if values[i] &gt;= values[child]:\n                break\n            values[i], values[child] = values[child], values[i]\n            i, k = child, ck\n\n    def ends(heaps):\n        total = -1\n        out = []\n        for k in heaps:\n            total += leo[k]\n            out.append(total)\n        return out\n\n    def order_roots(heaps):\n        changed = True\n        while changed:\n            changed = False\n            pos = ends(heaps)\n            for h in range(len(heaps) - 1, 0, -1):\n                if values[pos[h - 1]] &gt; values[pos[h]]:\n                    values[pos[h - 1]], values[pos[h]] = values[pos[h]], values[pos[h - 1]]\n                    sift(pos[h - 1], heaps[h - 1])\n                    changed = True\n\n    heaps = []\n    for i in range(len(values)):\n        if len(heaps) &gt;= 2 and heaps[-2] == heaps[-1] + 1:\n            k = heaps.pop()\n            heaps.pop()\n            heaps.append(k + 2)\n        else:\n            heaps.append(0 if heaps and heaps[-1] == 1 else 1)\n        sift(i, heaps[-1])\n        order_roots(heaps)\n    for end in range(len(values) - 1, 0, -1):\n        k = heaps.pop()\n        if k &gt;= 2:\n            heaps.append(k - 1)\n            heaps.append(k - 2)\n            order_roots(heaps)\n\nsamples = [[3, 1, 4, 2], [1, 2, 3, 4], [4, 3, 2, 1], [2, 2, 1]]\nfor sample in samples:\n    work = sample[:]\n    smoothsort(work)\n    assert work == sorted(sample)\nsmoothsort(samples[0])\nprint(*samples[0])\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\">Smoothsort is Dijkstra&#8217;s in-place adaptive heapsort: sorted input becomes linear. The adaptive sort that libraries ship is <strong>timsort<\/strong>. Smoothsort remains the heapsort that does not forget an already sorted run.<\/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 smoothsort when the input is random or when stability matters. Heapsort and timsort cover those two contracts with code that is easier to audit. Keep it when an in-place comparison sort must become linear on sorted input and the Leonardo layout is an acceptable implementation cost.<\/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 smoothsort returns the Leonardo heaps and the sorted-input linear bound that heapsort does not have. <strong>Smoothsort is an in-place heap sort whose cost drops to linear on sorted input because the unsorted prefix is a forest of Leonardo heaps.<\/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: Smoothsort keeps the unsorted prefix as a forest of implicit heaps whose sizes are Leonardo numbers, then peels maxima from the right. Sorted input costs \u0398(n). Every input costs O(n log n). The sort is in place and unstable. Dijkstra designed it so a heap sort would&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-257","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\/257","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=257"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/257\/revisions"}],"predecessor-version":[{"id":656,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/257\/revisions\/656"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=257"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=257"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=257"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}