Sub topic 8
Time and Space Complexity
This chapter assumes you already know the sift_down, build_max_heap, and heap_sort functions from the earlier chapters. You should also be comfortable with Big-O notation and with logarithms in base 2. Here we work out how much time heap sort takes and how much extra memory it needs, and we check those numbers by counting comparisons in real runs.
The Two Phases of the Cost
Heap sort runs in two separate phases, and each phase has its own cost:
- Build phase.
build_max_heapcallssift_downon every non-leaf node, from indexn // 2 - 1back to0. - Extraction phase. For
endfromn - 1down to1, heap sort swaps the root into positionendand callssift_down(a, 0, end).
The total running time is the sum of the two phases. To get it, we need to know how much one sift_down call costs.
Cost of One Sift-Down
sift_down moves one element downward, one level per loop iteration. A complete binary tree with n nodes has height floor(log2 n), so a call that starts at the root runs at most floor(log2 n) iterations.
Each iteration does a constant amount of work:
- up to two comparisons: one to choose the larger child, one to compare the root with that child
- at most one swap
A sift-down from the root therefore costs O(log n) time. A sift-down that starts at a node of height h costs O(h), because it can only go h levels down before it reaches a leaf. That fact matters for the build phase.
The Build Phase Is O(n)
A quick upper bound for the build phase would be about n/2 calls times O(log n) each, which gives O(n log n). That bound is correct but loose. Most nodes in a heap sit close to the bottom, where sift_down is cheap. Half the nodes are leaves and are skipped entirely. A quarter are one level above the leaves and move at most one step. Only the root can travel the full height.
Adding up these costs level by level gives a total of O(n). The chapter "Proving That Heap Construction Is Linear" derives that sum. For this chapter, you only need the result: building the heap costs O(n), at most about 2n comparisons with this sift_down.
The Extraction Phase Is O(n log n)
The extraction phase does n - 1 iterations. In each one, the heap holds end elements and the sift-down starts at the root, so it costs O(log end). Summing over all iterations:
log2(n-1) + log2(n-2) + ... + log2(1) = log2((n-1)!)
By Stirling's approximation, log2(n!) is about n log2 n − 1.44n, which is Θ(n log n). The heap shrinks as sorting proceeds, but for most of the run it is still large. The second half of the iterations each work on a heap of at least n/2 elements, which is still about log2 n levels deep. Shrinking the heap does not lower the order of growth.
Total: O(n) + O(n log n) = O(n log n).
Best, Average, and Worst Cases
Many sorting algorithms run faster or slower depending on how the input is arranged. Heap sort varies much less.
| Case | Time | When it happens |
|---|---|---|
| Worst | Θ(n log n) | Any input. No input makes it worse than this bound. |
| Average | Θ(n log n) | Random permutations of distinct keys |
| Best (distinct keys) | Θ(n log n) | Even already-sorted input, ascending or descending |
| Best (all keys equal) | Θ(n) | Every `sift_down` stops after its first comparison step |
| Extra space | O(1) | The iterative `sift_down` uses only a few index variables |
Two rows need explanation.
Sorted input does not help. Heap sort is not adaptive: an adaptive algorithm gets faster when its input is already partly ordered. Insertion sort is adaptive. Heap sort is not, because the extraction phase always moves a small leaf value to the root and then sifts it back down. Even when keys are distinct and the input is already sorted, heap sort's best case is still Θ(n log n). This is a known result, and the reason is that the element swapped to the root nearly always belongs near the bottom.
Equal keys are the exception. The test if a[root] >= a[child]: break stops immediately when every key is the same. Each sift_down call then does at most two comparisons, so the whole sort takes linear time. If many keys are duplicates but they are not all equal, you get something in between.
Measuring It: Counting Comparisons
The following program instruments sift_down to count comparisons between elements. It runs heap sort on four kinds of input and prints the counts next to n log2 n.
import math
import random
def sift_down_count(a, start, end, counter):
root = start
while True:
child = 2 * root + 1
if child >= end:
break
if child + 1 < end:
counter[0] += 1
if a[child + 1] > a[child]:
child += 1
counter[0] += 1
if a[root] >= a[child]:
break
a[root], a[child] = a[child], a[root]
root = child
def heap_sort_count(a):
counter = [0]
n = len(a)
for start in range(n // 2 - 1, -1, -1):
sift_down_count(a, start, n, counter)
build = counter[0]
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down_count(a, 0, end, counter)
extract = counter[0] - build
return build, extract
n = 1024
random.seed(1)
inputs = {
"random": random.sample(range(n), n),
"ascending": list(range(n)),
"descending": list(range(n, 0, -1)),
"all equal": [7] * n,
}
print(f"n = {n}, n*log2(n) = {int(n * math.log2(n))}")
for name, data in inputs.items():
build, extract = heap_sort_count(data)
assert data == sorted(data)
print(f"{name:>10}: build={build:6d} extract={extract:6d} total={build + extract:6d}")You can predict the "all equal" row exactly. In the build phase, 511 of the 512 internal nodes have two children, so each costs 2 comparisons. Node 511 has only one child and costs 1. That gives 1023. In the extraction phase, every call with end >= 3 costs 2, the call with end = 2 costs 1, and the call with end = 1 costs 0. That gives 2043. The total is 3066, about 3n.
The other three rows each come out somewhat under 2 × 10,240 = 20,480 comparisons in the extraction phase, and the three counts are close to one another. The descending input is already a max-heap, so its build phase does no swaps, but its extraction cost barely changes. That near-equality is what "not adaptive" means in practice.
Space Complexity
Heap sort is an in-place sort, which means it rearranges elements inside the input array instead of copying them into a new one. Its extra memory is:
- the loop variables
end,root, andchild - one temporary used by the swap
That is O(1) auxiliary space no matter how large n is. Merge sort needs an O(n) buffer, and quicksort needs O(log n) stack space even in a careful implementation. Of the three, only heap sort keeps the worst-case time at O(n log n) while using only O(1) extra space.
Hidden Costs: Memory Access Patterns
Asymptotic analysis counts operations, but real hardware also charges for memory access. Sift-down jumps from index i to index 2i + 1, so each step goes roughly twice as far into the array as the last. For large arrays, the first few levels stay in the CPU cache, but the deeper levels land on different cache lines and often miss.
Quicksort and merge sort mostly scan memory in order, and caches and prefetchers handle that pattern well. As a result, heap sort is often slower in practice than quicksort on large inputs even though it has the better worst-case bound. The chapter "Heap Sort vs. Quicksort and Merge Sort" picks this trade-off up again.
Common Mistakes in the Analysis
- Writing the build phase as O(n log n) and stopping there. That bound is true but loose. It does not change the total, but it gives the wrong answer if you are asked only for the cost of building the heap, for example when you build a heap to take the top k items.
- Assuming sorted input is a best case. Sorted input is a best case for insertion sort and a bad case for naive quicksort. For heap sort it is ordinary.
- Counting swaps but not comparisons. The descending input does almost no swaps during the build phase but still does Θ(n log n) comparisons overall.
- Calling a recursive implementation O(1) space. See the warning above.
Exercise
A colleague says heap sort's best case is O(n) because an already-sorted descending array is already a max-heap, so building the heap needs no swaps. What is right and what is wrong in this claim?
Show answer
The build phase on a descending array does need no swaps and costs O(n). But the extraction phase still runs n − 1 times. Each time it swaps a small leaf value into the root and sifts it down about log2 n levels. So the total is still Θ(n log n). The only input with a linear best case is one where every key is equal, or more generally where sift-downs stop right away.
Exercise
Using the instrumented code, about how many comparisons does the extraction phase do for n = 2^20 random keys, to within a factor of about 1.1? Show your reasoning.
Show answer
The extraction phase does at most about 2 comparisons per level, with about log2 n = 20 levels per sift-down and n − 1 sift-downs. That gives roughly 2 × 2^20 × 20 ≈ 42 million, and the real count lands a little below that, around 40 million. The build phase adds at most about 2n ≈ 2 million.
Exercise
Rewrite sift_down recursively and state its auxiliary space. Then explain why the iterative version in this tutorial uses O(1).
Show answer
def siftdownrec(a, root, end): child = 2*root+1; if child >= end: return; if child+1 < end and a[child+1] > a[child]: child += 1; if a[root] < a[child]: swap a[root] and a[child], then call siftdownrec(a, child, end). Each call can recurse once per level, so the stack can grow to O(log n) frames. The iterative version reuses the same root and child variables inside a while loop, so its memory use does not depend on n.