Heap sort
medium 18 minHeap sort turns the array into a max-heap in O(n), then repeatedly swaps the root (the maximum) to the end and sifts the new root down in O(log n).
See it run
Turn the array into a max-heap, then swap the root to the back and sift the new root down, n - 1 times.
Operations
Build the max-heap
Turn [4, 10, 3, 5, 1] into a max-heap in place. Start at the last parent and sift each node down, moving left towards the root.
Step 1 of 10
Five values in an array
- 40
- 101
- 32
- 53
- 14
Heap sort never builds a separate tree. It reads the array as a tree: slot 0 is the root and slot i has children at 2i + 1 and 2i + 2.
Step 1: Five values in an array
def heapify(arr, n, i): largest = i left, right = 2 * i + 1, 2 * i + 2 if left < n and arr[left] > arr[largest]: largest = left if right < n and arr[right] > arr[largest]: largest = right if largest != i: # a child is bigger arr[i], arr[largest] = arr[largest], arr[i] heapify(arr, n, largest) # keep sinkingdef build_max_heap(arr): n = len(arr) for i in range(n // 2 - 1, -1, -1): # last parent down to the root heapify(arr, n, i) return arrprint(build_max_heap([4, 10, 3, 5, 1]))# [10, 5, 3, 4, 1]- Time
- O(n)
- Space
- O(1)
- this run
- 6 comparisons, 2 swaps
- insert one by one
- O(n log n)
Build from the last parent backwards. Every node you heapify then has two children that are already heaps, which is the one thing heapify needs.
In the real world
The same heap sort doing real jobs. Pick one and step through it.
Four players, winners move up. The champion is the maximum; to find second place you only replay the champion's path.
Step 1 of 5
Four players, three matches
Players 3, 7, 2, 8 start at the bottom. Each match sends the bigger value up, like a parent that must beat its children.
Step 1: Four players, three matches
players = [3, 7, 2, 8]import heapqranking = []heap = [-p for p in players] # heapq is a min-heap: negate for maxheapq.heapify(heap) # O(n) "tournament"while heap: ranking.append(-heapq.heappop(heap)) # winner, then replay one pathprint(ranking) # [8, 7, 3, 2]Common mistakes
The bugs interviewers watch for, with the fix beside each.
Building the heap top-down
criticalSifting down only works when both children are already heaps. Going from the root forwards breaks that: [1, 2, 3, 4, 5, 6, 7] becomes [3, 5, 7, 4, 2, 6, 1], which is not a heap. Go from the last parent backwards.
Wrongfor i in range(n // 2): # root first: wrong heapify(arr, n, i)Rightfor i in range(n // 2 - 1, -1, -1): # last parent first heapify(arr, n, i)Heapifying with the full size after a swap
criticalAfter the max moves to slot end, it is no longer part of the heap. Passing n lets heapify see it as a child and pull it straight back to the root; the array never gets sorted.
Wrongfor end in range(n - 1, 0, -1): arr[0], arr[end] = arr[end], arr[0] heapify(arr, n, 0) # sorted values rejoin the heapRightfor end in range(n - 1, 0, -1): arr[0], arr[end] = arr[end], arr[0] heapify(arr, end, 0) # heap is slots 0..end-1One-based child formulas on a 0-based array
criticalChildren at 2i and 2i + 1 are for heaps that start at index 1. With Python's 0-based lists, index 0 would be its own left child and every parent-child link is off by one.
Wrongleft, right = 2 * i, 2 * i + 1Rightleft, right = 2 * i + 1, 2 * i + 2parent = (i - 1) // 2Stopping after one level
majorA swap can break the heap one level further down. Without the recursive call (or a loop) the small value stops halfway: [4, 10, 3, 5, 1] builds to [10, 4, 3, 5, 1], where 4 is still above 5.
Wrongif largest != i: arr[i], arr[largest] = arr[largest], arr[i] # forgot to continue downRightif largest != i: arr[i], arr[largest] = arr[largest], arr[i] heapify(arr, n, largest)Using a min-heap for ascending order
majorIn-place heap sort puts each extracted root at the back. A min-heap sends the smallest values to the back, so the result is descending: [10, 5, 4, 3, 1]. Use a max-heap for ascending.
Wrongif left < n and arr[left] < arr[smallest]: # min-heap smallest = leftRightif left < n and arr[left] > arr[largest]: # max-heap largest = leftCalling heapq a constant-space heap sort
minorPopping into a new list is a fine O(n log n) sort, but it builds a second list, so it is O(n) extra space, not the O(1) in-place algorithm.
Wrongout = [heapq.heappop(h) for _ in range(len(h))] # O(n) extraRightheap_sort(arr) # swaps inside arr: O(1) extra
Interview tips
How to explain it
- Two phases: build a max-heap in O(n), then n - 1 times swap the root to the end and sift down in O(log n).
- The array is split into a shrinking heap on the left and a growing sorted part on the right.
- O(n log n) best, average and worst; O(1) extra space; not stable; not adaptive.
Spot it in the wild
- Introsort falls back to heap sort when quick sort recurses too deep.
- Top-k problems: build once, extract only k times.
- Memory-tight or real-time code that needs a hard O(n log n) guarantee.
Memory tricks
- HEAP: Heapify, Extract, Adjust, Place.
- Children 2i + 1 and 2i + 2, parent (i - 1) // 2.
- Heap shrinks from the right, sorted grows from the right.
Watch out
- Build loop runs backwards from n // 2 - 1.
- Heapify with the shrunken size, never n, after a swap.
- Equal values can change order: do not use it when you need stability.