How smoothsort adapts a heap to sorted input

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 Θ(n). Every input costs O(n log n). 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.


What the problem actually asks

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.

Leonardo numbers supply the heap sizes. They obey L(0) = 1, L(1) = 1, and L(k) = L(k−1) + L(k−2) + 1. A heap of size L(k) is a root whose two children are heaps of sizes L(k−1) and L(k−2), laid out immediately to its left. That layout lives inside the array.


What the algorithm guarantees

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 Θ(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.

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’s, so the adaptive case is the reason to consider the algorithm at all.


The working steps

  1. 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.
  2. Store a heap of size L(k) as a heap of size L(k−1), then a heap of size L(k−2), then the root.
  3. Sift a new root so each Leonardo heap is a heap and the sequence of roots has its maximum at the rightmost root.
  4. 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.
  5. Repeat the extraction until the forest is empty. The emitted suffix is sorted.

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’s advantage over heapsort disappears on random data, where both are n log n and heapsort has the smaller constant.


Approaches that look simpler and fail

Approach Why it fails when a sorted array must become a linear heap sort
Ordinary heapsort Build and extract are Θ(n log n) on a sorted array. The Leonardo forest is what collapses that case to linear.
Any forest of fixed-size heaps 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.
Expect timsort’s constants on nearly sorted objects Smoothsort’s siftes jump through the Leonardo layout. A library that needs stability and speed on runs uses timsort.
Call the algorithm stable because sorted input is barely moved Disordered equal keys are still swapped by siftes. Stability is not part of the result.

A stable adaptive sort belongs to timsort. A simpler in-place n log n sort, with a worse sorted-input case, belongs to heapsort.


A working example

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 1 2 3 4.

def smoothsort(values):
    leo = [1, 1]
    while leo[-1] < len(values) + 2:
        leo.append(leo[-1] + leo[-2] + 1)

    def sift(i, k):
        while k > 1:
            left = i - leo[k - 2] - 1
            right = i - 1
            child, ck = (left, k - 1) if values[left] > values[right] else (right, k - 2)
            if values[i] >= values[child]:
                break
            values[i], values[child] = values[child], values[i]
            i, k = child, ck

    def ends(heaps):
        total = -1
        out = []
        for k in heaps:
            total += leo[k]
            out.append(total)
        return out

    def order_roots(heaps):
        changed = True
        while changed:
            changed = False
            pos = ends(heaps)
            for h in range(len(heaps) - 1, 0, -1):
                if values[pos[h - 1]] > values[pos[h]]:
                    values[pos[h - 1]], values[pos[h]] = values[pos[h]], values[pos[h - 1]]
                    sift(pos[h - 1], heaps[h - 1])
                    changed = True

    heaps = []
    for i in range(len(values)):
        if len(heaps) >= 2 and heaps[-2] == heaps[-1] + 1:
            k = heaps.pop()
            heaps.pop()
            heaps.append(k + 2)
        else:
            heaps.append(0 if heaps and heaps[-1] == 1 else 1)
        sift(i, heaps[-1])
        order_roots(heaps)
    for end in range(len(values) - 1, 0, -1):
        k = heaps.pop()
        if k >= 2:
            heaps.append(k - 1)
            heaps.append(k - 2)
            order_roots(heaps)

samples = [[3, 1, 4, 2], [1, 2, 3, 4], [4, 3, 2, 1], [2, 2, 1]]
for sample in samples:
    work = sample[:]
    smoothsort(work)
    assert work == sorted(sample)
smoothsort(samples[0])
print(*samples[0])

Where it is used

Smoothsort is Dijkstra’s in-place adaptive heapsort: sorted input becomes linear. The adaptive sort that libraries ship is timsort. Smoothsort remains the heapsort that does not forget an already sorted run.


When you can drop this algorithm

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.


Why this stays published

We publish this so a search for smoothsort returns the Leonardo heaps and the sorted-input linear bound that heapsort does not have. 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.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *