Sub topic 8
Time and Space Complexity
This chapter assumes you know Big-O notation and have read the earlier chapters on sift_down, build_max_heap, and heap_sort. Here we count the work those functions do and the memory they need.
Where the Time Goes
Heap sort runs in two phases, and each has its own cost.
Phase 1: Building the heap
build_max_heap calls sift_down on about n/2 nodes. A quick estimate puts each call at O(log n), so the whole phase is O(n log n). The true bound is tighter. Most nodes sit near the bottom of the tree and can only move a level or two, so the build phase is O(n). A later chapter proves this. For the total cost, the looser O(n log n) estimate is enough, because the second phase costs that much anyway.
Phase 2: Extracting the maximum
The loop runs n − 1 times. Each pass does one swap and one sift_down from the root. The heap has height ⌊log₂ k⌋ when it holds k elements, and sift-down moves down at most one level per step with two comparisons per level. The pass costs O(log k), and the sum over all passes is
log₂(n−1) + log₂(n−2) + … + log₂ 1 = log₂((n−1)!) = Θ(n log n).
Adding the two phases gives O(n) + O(n log n) = O(n log n).
Best, Average, and Worst Case
| Case | Time | Why |
|---|---|---|
| Worst | O(n log n) | Every sift-down travels the full height |
| Average | Θ(n log n) | A random root replacement usually sinks close to a leaf |
| Best (distinct keys) | Θ(n log n) | Even sorted input gets scrambled by the build phase |
| Best (all keys equal) | O(n) | Every sift-down stops after its first comparison |
Unlike insertion sort, heap sort gets no speedup from input that is already sorted. The build phase rearranges the array into heap order whatever its starting order, and the element swapped to the root comes from the bottom level, so it is small and usually sinks most of the way back down.
You can see this by counting comparisons:
import random
def heap_sort_count(a):
count = 0
def sift_down(start, end):
nonlocal count
root = start
while True:
child = 2 * root + 1
if child >= end:
break
if child + 1 < end:
count += 1
if a[child + 1] > a[child]:
child += 1
count += 1
if a[root] >= a[child]:
break
a[root], a[child] = a[child], a[root]
root = child
n = len(a)
for start in range(n // 2 - 1, -1, -1):
sift_down(start, n)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(0, end)
return count
n = 1024
inputs = {
"sorted": list(range(n)),
"reversed": list(range(n, 0, -1)),
"random": random.sample(range(n), n),
"all equal": [7] * n,
}
for name, data in inputs.items():
print(f"{name:>10}: {heap_sort_count(data)} comparisons")The sorted, reversed, and random inputs all give comparison counts of the same order, close to 2n log₂ n. Only the all-equal input drops to a few thousand comparisons, which is linear in n.
Space Complexity
Heap sort needs O(1) extra space. The heap lives inside the input array, the sorted part grows from the right end, and the only other storage is a few index variables.
Exercise
A colleague says that heap sort on an already-sorted array of n distinct keys should run in O(n), because "the data is already in order." Explain why that is wrong, and name an input that does make heap sort run in O(n).
Show answer
Ascending order is not heap order. The build phase has to rearrange the array into a max-heap, and in each extraction the element swapped to the root comes from the bottom level. It is small, so it usually sinks close to a leaf and costs O(log n) per pass. The total stays Θ(n log n). An array where every key is equal runs in O(n), because every sift-down stops after one comparison.
Exercise
How much extra memory does heap sort use if sift_down is written recursively, and why?
Show answer
O(log n). Each recursive call moves one level down the tree and adds a stack frame, and the tree's height is ⌊log₂ n⌋.