How heapsort sorts in place in n log n

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 Θ(n). The n extractions are Θ(n log n) 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.


What the problem actually asks

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.

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.


What the algorithm guarantees

Floyd’s heapify, from the last parent at index floor(n/2)−1 down to the root, runs in Θ(n) comparisons. Each of the n−1 extractions sifts a root down a tree of height floor(log₂ of the current size), so the sort is Θ(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).

The result is unstable: sifting swaps equal keys according to their positions in the tree. Cache behavior is weaker than quicksort’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.


The working steps

  1. Index the array from 0. The parent of i is floor((i−1)/2). The children of i are 2i+1 and 2i+2.
  2. Sift down from index floor(n/2)−1 through 0. Sift down swaps a node with its larger child until the parent is at least both children or a leaf is reached.
  3. The array is now a max-heap. The maximum sits at index 0.
  4. For end from n−1 down to 1, swap index 0 with end, and sift down on the prefix of length end.
  5. The swapped value at end is in its final place. When the prefix has length 1, the array is sorted ascending.

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.


Approaches that look simpler and fail

Approach Why it fails when an in-place n log n sort is required
Insert n keys into an empty heap, one by one, and call the build linear n insertions cost Θ(n log n). The linear bound is the bottom-up sift from the last parent.
Sift up during the bottom-up build Sift up repairs one leaf-to-root path per node and reintroduces an n log n build. The construction sift moves the hole downward.
Stop after the heap exists A heap is only partially ordered. The parent rule fixes the root. The sorted array is produced by the extractions.
Expect equal keys to keep their order A sift compares positions in the tree and swaps those records. Equals move.

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.


A working example

The Bash script and the Python script heapsort in place. Children of index i are 2i+1 and 2i+2. Both print 1 2 3 4 5.

a=(3 1 4 5 2)
n=${#a[@]}
sift() {
  local i=$1 end=$2 left right best t
  while :; do
    left=$((2*i+1)); right=$((2*i+2)); best=$i
    if (( left < end && a[left] > a[best] )); then best=$left; fi
    if (( right < end && a[right] > a[best] )); then best=$right; fi
    if (( best == i )); then return; fi
    t=${a[i]}; a[i]=${a[best]}; a[best]=$t
    i=$best
  done
}
for ((i=n/2-1; i>=0; i--)); do sift "$i" "$n"; done
for ((end=n-1; end>0; end--)); do
  t=${a[0]}; a[0]=${a[end]}; a[end]=$t
  sift 0 "$end"
done
echo "${a[*]}"
def heapsort(a):
    n = len(a)

    def sift(i, end):
        while True:
            left, right = 2 * i + 1, 2 * i + 2
            best = i
            if left < end and a[left] > a[best]:
                best = left
            if right < end and a[right] > a[best]:
                best = right
            if best == i:
                return
            a[i], a[best] = a[best], a[i]
            i = best

    for i in range(n // 2 - 1, -1, -1):
        sift(i, n)
    for end in range(n - 1, 0, -1):
        a[0], a[end] = a[end], a[0]
        sift(0, end)
    return a

a = heapsort([3, 1, 4, 5, 2])
assert a == [1, 2, 3, 4, 5]
print(*a)

Where it is used

Heapsort is the in-place fallback inside introsort, the algorithm of C++ std::sort, once recursion gets too deep. The Linux kernel’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.


When you can drop this algorithm

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.


Why this stays published

We publish this so a search for heapsort returns the linear heapify and the n log n extractions as separate phases. 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.

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

Leave a Reply

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