A heap gives the smallest or largest item fast. Greedy algorithms and shortest paths lean on it.
Open the interactive lessons →Heaps and Priority Queues past questions
Contents
- What a heap is: shape, rule and the array
- Insertion: put it at the end, then sift up
- Deleting the root: move the last up, then sift down
- Where can the largest, smallest or k-th element be?
- Building a heap and heap sort
1. What a heap is: shape, rule and the array
A heap is a tree that is always filled left to right, and where every parent beats its children. It is not sorted.
A binary heap: a complete binary tree stored in an array, with an ordering rule between a parent and its children.
The question this lesson answers. How can a tree live in a plain array?
| New word | Meaning |
|---|---|
| complete tree | levels filled from left to right with no gaps |
| heap order | every parent is at least as good as its children |
| index | the position of a node in the array |
A priority queue is a container where you always want the smallest (or largest) item next: a hospital queue where the most urgent patient is served first. A binary heap is the standard way to build one. It answers "what is the minimum?" instantly and supports insert and remove-minimum in $O(\log n)$ time.
Two rules define a binary heap.
Shape rule (complete tree): every level is full except possibly the last, and the last level is filled from the left with no gaps.
Order rule: in a min-heap every parent is $\le$ its children. In a max-heap every parent is $\ge$ its children.
Why it works. Because the tree is filled level by level with no gaps, positions follow from arithmetic and no links are needed.
The order rule only links a parent with its own children. Siblings and cousins have no order between them. So a heap is not a sorted list and not a BST. This is the source of many exam traps.
Why store it in an array? Because of the shape rule there are no gaps, so the tree can be laid out level by level in a plain list. With 0-based indices the family relations are pure arithmetic:
For the node at index $i$ (0-indexed):
parent $=\lfloor (i-1)/2\rfloor$ left child $=2i+1$ right child $=2i+2$
A child exists only if its index is less than $n$.
Index arithmetic on the example (n = 9)
| index $i$ | value | parent $\lfloor(i-1)/2\rfloor$ | left $2i+1$ | right $2i+2$ |
|---|---|---|---|---|
| 0 | 2 | - | 1 | 2 |
| 1 | 5 | 0 | 3 | 4 |
| 2 | 10 | 0 | 5 | 6 |
| 3 | 15 | 1 | 7 | 8 |
| 4 | 7 | 1 | - | - |
| 5 | 20 | 2 | - | - |
| 6 | 25 | 2 | - | - |
| 7 | 18 | 3 | - | - |
| 8 | 19 | 3 | - | - |
Some books use 1-based indices (children $2i$ and $2i+1$). The PYQs here say "0-indexed", so always use $2i+1$ and $2i+2$.
| Fact (heap with $n$ elements, 0-indexed) | Formula | Example $n=9$ |
|---|---|---|
| last index | $n-1$ | 8 |
| parent of the last element | $\lfloor(n-2)/2\rfloor$ | 3 |
| internal nodes (have a child) | indices $0\dots\lfloor n/2\rfloor-1$ | 0 to 3 |
| leaves | indices $\lfloor n/2\rfloor\dots n-1$ | 4 to 8 (5 leaves) |
| number of leaves | $\lceil n/2\rceil$ | 5 |
| height (empty = 0) | $\lfloor\log_2 n\rfloor+1$ | 4 |
| max elements in height $h$ | $2^h-1$ | 15 for $h=4$ |
| min elements in height $h$ | $2^{h-1}$ | 8 for $h=4$ |
Why at least $2^{h-1}$ elements for height $h$? All levels above the last are full: $1+2+\dots+2^{h-2}=2^{h-1}-1$ nodes. The last level has at least one node, so $n\ge2^{h-1}$. For height 9 that is $2^8=256$ (a PYQ).
Analogy: a tournament ladder or company chart where the boss of every group is the strongest of that group. Limit: in a real company two bosses of different teams can be ranked either way; a heap also says nothing about people on the same level.
| Min-heap | Max-heap | BST | Sorted array | |
|---|---|---|---|---|
| order rule | parent $\le$ children | parent $\ge$ children | left < node < right | $a_i\le a_{i+1}$ |
| shape | complete | complete | any | n/a |
| stored as | array | array | linked nodes | array |
| minimum | root, $O(1)$ | a leaf, $O(n)$ | leftmost, $O(h)$ | first, $O(1)$ |
| maximum | a leaf, $O(n)$ | root, $O(1)$ | rightmost, $O(h)$ | last, $O(1)$ |
| insert | $O(\log n)$ | $O(\log n)$ | $O(h)$ | $O(n)$ |
| in-order gives sorted? | no | no | yes | yes |
| Common mistake | Correction |
|---|---|
| reading a heap array as sorted | only parent-child pairs are ordered |
| using $2i$ and $2i+1$ in a 0-indexed array | use $2i+1$ and $2i+2$ |
| placing a new node anywhere | always the first free slot (next index) |
| thinking the max of a min-heap is the last element | it is some leaf, not necessarily the last |
Worked example: Read a heap array
Problem.
Is [3, 8, 5, 10, 9, 6, 7] a min-heap?
Idea.
Check every parent against its two children.
- Index 0 (3): children 8, 5: ok.
- Index 1 (8): children 10, 9 (indices 3, 4): ok.
- Index 2 (5): children 6, 7 (indices 5, 6): ok.
- No node has a larger index to check.
Answer.
yes, it is a min-heap
Common mistake.
Checking only consecutive elements instead of parent-child pairs.
Worked example: Find the bad pair
Problem.
Which pair breaks the min-heap rule in [3, 5, 4, 9, 12, 16, 10, 7]?
Idea.
Compare every child with its parent, down to the last index.
- Index 7 holds 7. Its parent is index $\lfloor 6/2\rfloor=3$, which holds 9.
- The child 7 is smaller than its parent 9.
Answer.
indices 3 and 7
Common mistake.
Stopping after the first few levels.
Worked example: A heap need not be sorted
Problem.
Is $[1,5,2,9,6,3]$ a min-heap?
Idea.
Compare each element only with its parent.
- 1 is not greater than 5 or 2.
- 5 is not greater than 9 or 6.
- 2 is not greater than 3.
Answer.
Yes, although the list is not sorted.
Common mistake.
Rejecting it because 5 comes before 2.
- Draw the array level by level in groups of 1, 2, 4, 8. The tree appears at once.
- To test a heap, compare each element from index 1 with its parent at $\lfloor(i-1)/2\rfloor$.
- Check the indexing: starting at 0 the children are $2i+1$ and $2i+2$.
Children of i are at 2i+1 and 2i+2.
| Step | Method for any exam question |
|---|---|
| 1 | Check the shape: no gaps. |
| 2 | Find children and parent by index. |
| 3 | Check the order rule at every parent. |
2. Insertion: put it at the end, then sift up
Drop it in the next free slot, then keep swapping it with its parent while it beats the parent.
How a new element enters a heap and why the repair walks up one path.
The question this lesson answers. Where does a new item go?
| New word | Meaning |
|---|---|
| sift up | swap with the parent while out of order |
| last position | the next free slot of the array |
| path to the root | the only nodes an insertion can move |
A new employee starts at the bottom and is promoted while they outrank their manager.
To keep the shape complete, the new element must go in the first free slot, which is index $n$ (the end of the array). That may break the order rule between the new node and its parent. The repair is sift-up (also called bubble-up or heapify-up).
Why it works. Adding at the end keeps the shape; only the path to the root can break the order.
insert into a min-heap
def insert(heap, x):
heap.append(x) # step 1: first free slot
i = len(heap) - 1
while i > 0:
p = (i - 1) // 2 # parent index
if heap[i] < heap[p]: # min-heap rule broken?
heap[i], heap[p] = heap[p], heap[i] # swap up
i = p # continue from the parent
else:
break # rule holds: stop
Why does this work? Before the insert the heap is correct. Only the new node can be wrong, and only against its parent. A swap moves the new value up and the old parent value down. The old parent stays valid there, because it was already $\le$ everything below it. The new value is smaller still, so it is also $\le$ the sibling's subtree. So the only possible violation moves one level up. After at most $h$ steps we reach the root or stop.
Insert 3 into the min-heap [5, 8, 11, 15, 20]
A valid min-heap
[5, 8, 11, 15, 20]. We will insert 3.Put 3 in the first empty slot, index 5, so the tree stays complete. Only this spot can break the heap rule.
The child 3 is smaller than its parent 11 (index 2), so the min-heap rule is broken: swap.
3 moved up to index 2. Check it against its new parent.
The child 3 is smaller than its parent 5 (index 0), so the min-heap rule is broken: swap.
3 moved up to index 0. Check it against its new parent.
Heap restored:
[3, 8, 5, 15, 20, 11]. The new value reached the root.
| Case | Swaps | Cost |
|---|---|---|
| new value $\ge$ its parent | 0 | $O(1)$ (best) |
| new value is the new minimum | $h-1$ (up to the root) | $O(\log n)$ (worst) |
| average for random data | about 1 to 2 | $O(1)$ expected |
Complexity derived. The loop runs at most once per level, and a heap with $n$ elements has $\lfloor\log_2n\rfloor+1$ levels, each step costs $O(1)$. So insert is $O(\log n)$ in the worst case.
Insert 12 into a min-heap
| step | array | action |
|---|---|---|
| 0 | [10, 18, 14, 25, 31, 29, 22, 27, 40] | start |
| 1 | [10, 18, 14, 25, 31, 29, 22, 27, 40, 12] | append at index 9 |
| 2 | [10, 12, 14, 25, 18, 29, 22, 27, 40, 31] | swap with 31, then with 18; stop below 10 |
Worked example: Insert into a min-heap
Problem.
Insert 4 into [2, 6, 5, 9, 8].
Idea.
Append, compare with parent.
- Array
[2, 6, 5, 9, 8, 4], new index 5. - Parent index 2 (value 5): 4 < 5, swap:
[2, 6, 4, 9, 8, 5]. - Parent index 0 (value 2): 4 > 2, stop.
Answer.
[2, 6, 4, 9, 8, 5]
Common mistake.
Comparing with the sibling instead of the parent.
Worked example: Insert a new maximum into a max-heap
Problem.
Insert 50 into the max-heap [40, 30, 35, 10, 20].
Idea.
Max-heap: swap while the child is larger.
- Append:
[40, 30, 35, 10, 20, 50], index 5. - Parent index 2 (35): 50 > 35 swap:
[40, 30, 50, 10, 20, 35]. - Parent index 0 (40): 50 > 40 swap:
[50, 30, 40, 10, 20, 35]. Root reached.
Answer.
[50, 30, 40, 10, 20, 35]
Common mistake.
Using the min-heap comparison on a max-heap.
Last-inserted question. If a PYQ asks "which element could have been the last inserted", the answer must lie on the path from the last index up to the root of the final heap. Elements off that path cannot have just moved. Then undo the swaps to check the earlier heap is valid.
| Common mistake | Correction |
|---|---|
| inserting at the root | always at index $n$ |
| swapping with the smaller sibling | compare only with the parent |
| continuing after the rule holds | stop at the first parent that is $\le$ |
Worked example: Two ways to build, two arrays
Problem.
Build a min-heap from $3,2,1$ by inserting one at a time, and by sifting down from the bottom. Are the arrays equal?
Idea.
Different procedures may give different valid heaps.
- Inserting: $[3]$, then $[2,3]$, then $[1,3,2]$.
- Bottom-up on $[3,2,1]$: the root swaps with 1, giving $[1,2,3]$.
Answer.
$[1,3,2]$ and $[1,2,3]$: both are valid heaps.
Common mistake.
Assuming there is only one heap for a set of keys.
End, then up.
| Step | Method for any exam question |
|---|---|
| 1 | Put it at the end. |
| 2 | Compare with the parent. |
| 3 | Swap while it beats the parent. |
3. Deleting the root: move the last up, then sift down
Take out the root, put the last element in its place, and push it down by swapping with the better child.
How delete_min (or delete_max) removes the root and repairs the heap.
The question this lesson answers. How is the top item removed without leaving a hole?
| New word | Meaning |
|---|---|
| root | the smallest (or largest) item |
| sift down | swap with the better child while out of order |
| better child | the smaller one in a min-heap, the larger in a max-heap |
The top post falls vacant: the last person is placed there and moves down until nobody below deserves the post more.
The root holds the answer, so removing it leaves a hole at index 0. If we simply pulled up a child, the hole would move down and gaps would appear. Instead we fill the hole with the last element (this keeps the tree complete), then fix the order rule by sift-down.
Why it works. Moving the last item to the root keeps the shape; only one downward path needs repair.
delete_min
def delete_min(heap):
root = heap[0]
heap[0] = heap[-1] # last element to the root
heap.pop() # shrink: shape is complete again
i, n = 0, len(heap)
while True:
l, r, smallest = 2*i + 1, 2*i + 2, i
if l < n and heap[l] < heap[smallest]: smallest = l
if r < n and heap[r] < heap[smallest]: smallest = r
if smallest == i: break # rule holds
heap[i], heap[smallest] = heap[smallest], heap[i]
i = smallest
return root
Swap with the smaller child in a min-heap (the larger child in a max-heap). If you swap with the bigger child, that child becomes the parent of its smaller sibling and breaks the rule.
delete_min on [3, 7, 11, 16, 9, 22, 28, 19, 20]
A valid min-heap.
delete_minmust return the root 3.The root leaves a hole. We fill it with the last element, 20, so no gap appears in the array.
The array shrinks to 8 items. The shape is complete, but the new root may be too big.
Children of 20: 7 and 11. The smaller child 7 beats the parent, so swap them.
7 rose to index 0; 20 sank to index 1. Keep checking it.
Children of 20: 16 and 9. The smaller child 9 beats the parent, so swap them.
9 rose to index 1; 20 sank to index 4. Keep checking it.
20 has no children inside the heap, so sift-down stops.
Done:
[7, 9, 11, 16, 20, 22, 28, 19]. The new minimum 7 is back at the root.
Complexity derived. Each loop iteration moves down one level and does constant work (two comparisons, one swap). There are at most $\lfloor\log_2n\rfloor$ moves, so delete is $O(\log n)$. Finding the minimum (without deleting) is $O(1)$: it is heap[0].
| Operation | Min-heap time | Why |
|---|---|---|
| find min | $O(1)$ | root |
| delete min | $O(\log n)$ | sift-down one path |
| insert | $O(\log n)$ | sift-up one path |
| find max | $O(n)$ | must scan all leaves |
| update value at a known index | $O(\log n)$ | sift up if smaller, sift down if larger |
| search for an arbitrary value | $O(n)$ | no ordering across branches |
| second smallest | $O(1)$ | smaller of the two root children |
Worked example: delete_min
Problem.
Delete the minimum from [1, 3, 2, 7, 4].
Idea.
Last to root, sift down.
- Move 4 to the root:
[4, 3, 2, 7]. - Children of 4: 3 and 2. Smaller is 2: swap:
[2, 3, 4, 7]. - Index 2 has no children (n = 4). Done.
Answer.
[2, 3, 4, 7]
Common mistake.
Swapping with 3 (the left child) instead of the smaller child 2.
Worked example: Two operations in a row
Problem.
Min-heap [4, 9, 25, 60, 41, 31, 27, 70]: delete_min, then insert(8).
Idea.
Finish the first operation completely before starting the second.
- delete_min: the last item 70 moves to the root and sinks, swapping with the smaller child each time.
- After the delete:
[9, 41, 25, 60, 70, 31, 27]. - insert(8): append it, then swap upwards while it is smaller than its parent.
Answer.
[8, 9, 25, 41, 70, 31, 27, 60]
Common mistake.
Inserting before the delete has finished sinking.
| Common mistake | Correction |
|---|---|
| moving the smaller child up and leaving a gap | always move the last element to the root |
| swapping with the larger child in a min-heap | smaller child |
| forgetting to pop the last slot | the array must shrink by one |
| sifting down when the children do not exist | a node at index $\ge\lfloor n/2\rfloor$ is a leaf |
Worked example: Swap with the smaller child
Problem.
Delete the minimum from $[1,5,2,9,6,3]$.
Idea.
The element sinking must swap with the smaller of its children.
- Move 3 to the root: $[3,5,2,9,6]$.
- The children are 5 and 2; swap with 2.
- 3 now has no child, so stop.
Answer.
$[2,5,3,9,6]$
Common mistake.
Swapping with the left child 5, which would put 5 above 2.
- Move the last element to the root, not a child of the root.
- In every swap pick the better child first, then compare it with the moving element.
- Count the elements afterwards: one delete removes exactly one.
Last to the top, then down.
| Step | Method for any exam question |
|---|---|
| 1 | Remove the root. |
| 2 | Move the last item there. |
| 3 | Swap with the better child until the order holds. |
4. Where can the largest, smallest or k-th element be?
In a min-heap the largest is always in the leaf layer; the second smallest is always next to the root.
Reasoning about positions and costs in a heap without running operations.
The question this lesson answers. Without sorting, where can a given item be?
| New word | Meaning |
|---|---|
| second best | always a child of the root |
| leaf range | indices $\lfloor n/2\rfloor$ to $n-1$ |
| k-th element | can be at depth at most $k-1$ |
In a knockout tree the champion is at the top, but the weakest player can only be someone who beat nobody, that is, at a leaf.
Fact 1: the extreme opposite to the root is in a leaf. In a min-heap an internal node has a child that is $\ge$ it, so an internal node cannot be the largest (it would have a child at least as large, but values are distinct, so a strictly larger child exists). Therefore the largest element sits in a leaf (indices $\lfloor n/2\rfloor$ to $n-1$). It need not be at the lowest level: a leaf can also exist on the level above.
Why it works. The order rule relates only parents and children, which limits where extremes can sit and says nothing about siblings.
Example of a leaf above the last level: min-heap [1, 2, 9, 3] has 4 elements, leaves are indices 2 and 3. Largest is 9 at index 2, which is on level 2 while 3 is on level 3. So "the largest is always at the lowest level" is false, while "always at a leaf" is true.
Fact 2: the second smallest is a child of the root. Remove the root: the next smallest must be a root of some subtree, and only the root children qualify. It is either the left or the right child. So finding the second minimum is $O(1)$ (compare two numbers).
Fact 3: the third smallest is a child of the root or a child of the second smallest, not necessarily a child of the root.
| Statement about a min-heap with distinct values | True? | Reason |
|---|---|---|
| the largest is at a leaf | true | an internal node has a larger child |
| the largest is at the lowest level | false | may be a leaf on the level above |
| the second smallest is a child of the root | true | Fact 2 |
| finding the largest takes $O(\log n)$ | false | needs scanning all leaves: $O(n)$ |
| inserting takes $O(\log n)$ | true | sift-up |
| deleting the minimum takes $O(1)$ | false | sift-down is $O(\log n)$ |
| update the value at a known index is $O(\log n)$ | true | one sift |
The same facts hold for a max-heap with "smallest" and "largest" swapped: the smallest is at a leaf, the second largest is a child of the root, finding the minimum is $O(n)$, and the PYQ "most efficient algorithm for the minimum of a max-heap" is $O(n)$ (scan the leaves; you cannot do better than looking at about $n/2$ values).
Index ranges. In a heap of 60 elements (indices 0 to 59) the leaves are indices 30 to 59. The largest of a min-heap must be in 30..59. So "the largest element can not be between" A[0]..A[14] and A[15]..A[29], which are internal nodes.
60 elements: where the maximum cannot be
| index range | all internal? | can hold the maximum? |
|---|---|---|
| A[0] to A[14] | yes (internal, < 30) | no |
| A[15] to A[29] | yes (internal, < 30) | no |
| A[30] to A[44] | no, leaves | yes |
| A[45] to A[59] | no, leaves | yes |
Worked example: Leaves of a heap with 10 elements
Problem.
Which indices are leaves, and where can the largest value of a min-heap be?
Idea.
$\lfloor n/2\rfloor$.
- $\lfloor10/2\rfloor=5$, so indices 5 to 9 are leaves.
- The largest is in one of them.
Answer.
indices 5 to 9
Worked example: Which statement is true?
Problem.
Max-heap, distinct elements: "the second-largest element is always a child of the root". True or false?
Idea.
Remove the root.
- After removing the root the next largest must be the top of a subtree, so one of the two children of the root.
- True.
Answer.
true
Common mistake.
Believing the third largest is also always a child of the root: it can be a grandchild.
| Common mistake | Correction |
|---|---|
| "the maximum of a min-heap is the last array element" | it is some leaf |
| "find max in a min-heap is $O(\log n)$" | it is $O(n)$ |
| "second smallest needs a delete" | it is a root child, $O(1)$ |
Mnemonic "Far side = Leaf": the extreme opposite to the root always hides among the leaves; the next extreme is always beside the root.
Worked example: The third smallest is not fixed
Problem.
Is $[1,2,5,3]$ a min-heap, and at what depth is its third smallest element? (The root has depth 0.)
Idea.
The rule only orders parents and children.
- 1 is above 2 and 5; 2 is above 3.
- The third smallest is 3, at index 3.
- Index 3 is two steps below the root.
Answer.
Yes; depth 2.
Common mistake.
Assuming the third smallest must be a child of the root.
Second best touches the root; the opposite extreme is a leaf.
| Step | Method for any exam question |
|---|---|
| 1 | Use the parent rule to narrow the positions. |
| 2 | Check leaves for the opposite extreme. |
5. Building a heap and heap sort
Heap sort = build a max-heap, then repeatedly move the maximum to the end.
Turning any array into a heap, and sorting with a heap.
The question this lesson answers. How does a heap sort an array?
| New word | Meaning |
|---|---|
| heapify | turning an array into a heap from the bottom up |
| in place | using only constant extra memory |
| stable | equal items keep their original order |
Repeatedly taking the winner off the podium and placing them at the end of the line.
Build-heap. Given any array, we can make it a heap in $O(n)$ time: run sift-down on every internal node, starting from the last internal node (index $\lfloor n/2\rfloor-1$) and going back to index 0. Leaves are already one-element heaps.
Why it works. Building from the bottom is cheap because most nodes are near the leaves; each removal then places one item in its final position.
Build a max-heap from [4, 10, 3, 5, 1, 8, 7]
This array is not a heap yet. Leaves are already tiny heaps, so we begin at the last internal node, index 2.
Both subtrees under index 2 are max-heaps. Now push 3 down to where it belongs.
Children of 3: 8 and 7. The larger child 8 beats the parent, so swap them.
8 rose to index 2; 3 sank to index 5. Keep checking it.
3 has no children inside the heap, so sift-down stops.
Both subtrees under index 1 are max-heaps. Now push 10 down to where it belongs.
Children of 10: 5 and 1. Neither beats it, so the rule holds and sift-down stops.
Both subtrees under index 0 are max-heaps. Now push 4 down to where it belongs.
Children of 4: 10 and 8. The larger child 10 beats the parent, so swap them.
10 rose to index 0; 4 sank to index 1. Keep checking it.
Children of 4: 5 and 1. The larger child 5 beats the parent, so swap them.
5 rose to index 1; 4 sank to index 3. Keep checking it.
4 has no children inside the heap, so sift-down stops.
Every internal node is fixed:
[10, 5, 8, 4, 1, 3, 7]is a max-heap, built bottom-up in $O(n)$ total.
Why $O(n)$, not $O(n\log n)$? A node at height $k$ (distance to the deepest leaf below) sinks at most $k$ levels. In a perfect tree with 15 nodes: 8 leaves (height 0, no work), 4 nodes of height 1, 2 of height 2, 1 of height 3. Worst-case swaps $=4\cdot1+2\cdot2+1\cdot3=11<15$. In general $\sum_k \frac n{2^{k+1}}\cdot k\le n\sum_{k\ge0}\frac k{2^{k+1}}=n$. Most nodes are near the bottom, where sinking is cheap.
heap sort (in place, uses a max-heap)
def heap_sort(a):
n = len(a)
for i in range(n // 2 - 1, -1, -1): # build a max-heap
sift_down(a, i, n)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0] # max goes to its final place
sift_down(a, 0, end) # repair the smaller heap a[0:end]
def sift_down(a, i, n): # max-heap version, heap is a[0:n]
while 2 * i + 1 < n:
c = 2 * i + 1
if c + 1 < n and a[c + 1] > a[c]:
c += 1 # take the larger child
if a[i] >= a[c]:
break
a[i], a[c] = a[c], a[i]
i = c
Full heap sort of [3, 9, 2, 7, 5]
| step | heap part | sorted tail |
|---|---|---|
| build: sift index 1 | [3, 9, 2, 7, 5] | - |
| build: sift index 0 | [9, 7, 2, 3, 5] | - |
| round 1: move 9 to index 4, heap [5, 7, 2, 3] → sift root | [7, 5, 2, 3] | [9] |
| round 2: move 7 to index 3, heap [3, 5, 2] → sift root | [5, 3, 2] | [7, 9] |
| round 3: move 5 to index 2, heap [2, 3] → sift root | [3, 2] | [5, 7, 9] |
| round 4: move 3 to index 1, heap [2] → sift root | [2] | [3, 5, 7, 9] |
Cost. Build-heap $O(n)$ plus $n-1$ rounds of sift-down each $O(\log n)$: total $O(n\log n)$. This holds for every input order: there is no lucky case, so best, average and worst are all $\Theta(n\log n)$. Extra memory is $O(1)$, so heap sort is in place.
Heap sort is not stable. Equal keys can swap their relative order, because the root-to-end swap jumps over many elements. Example: [2a, 2b, 1] sorted by value may put 2b before 2a.
| Property | Heap sort | Merge sort | Quick sort (first pivot) |
|---|---|---|---|
| best | $n\log n$ | $n\log n$ | $n\log n$ |
| worst | $n\log n$ | $n\log n$ | $n^2$ |
| extra space | $O(1)$ (in place) | $O(n)$ | $O(n)$ stack in the worst case ($O(\log n)$ on average) |
| stable? | no | yes | no |
| depends on input order? | no | no | yes |
| Heap sort statement | True? | Reason |
|---|---|---|
| $O(n\log n)$ irrespective of the input | true | no best case shortcut |
| $O(n^2)$ worst, $O(n\log n)$ best | false | worst is also $n\log n$ |
| in-place | true | swaps inside the array |
| not stable | true | the long-distance swap |
After build-heap the max is at the root
| step | array | heap part | sorted part |
|---|---|---|
| 0 | [10, 5, 8, 4, 1, 3, 7] | all heap |
Now drain it. Swap the root with the last heap slot, shrink the heap by one, and sift the new root down. The heap | sorted boundary moves one step left each round.
Heap Sort: drain the max-heap [10, 5, 8, 4, 1, 3, 7]
A max-heap: the largest value 10 is at the root. The sorted part on the right is still empty.
10 is the largest left, so its final place is index 6. Swap it there.
10 is fixed (green). The heap shrinks to 6 items; the new root may break the rule.
Children of 7: 5 and 8. The larger child 8 beats the parent, so swap them.
8 rose to index 0; 7 sank to index 2. Keep checking it.
Children of 7: 3. Neither beats it, so the rule holds and sift-down stops.
8 is the largest left, so its final place is index 5. Swap it there.
8 is fixed (green). The heap shrinks to 5 items; the new root may break the rule.
Children of 3: 5 and 7. The larger child 7 beats the parent, so swap them.
7 rose to index 0; 3 sank to index 2. Keep checking it.
3 has no children inside the heap, so sift-down stops.
7 is the largest left, so its final place is index 4. Swap it there.
7 is fixed (green). The heap shrinks to 4 items; the new root may break the rule.
Children of 1: 5 and 3. The larger child 5 beats the parent, so swap them.
5 rose to index 0; 1 sank to index 1. Keep checking it.
Children of 1: 4. The larger child 4 beats the parent, so swap them.
4 rose to index 1; 1 sank to index 3. Keep checking it.
1 has no children inside the heap, so sift-down stops.
5 is the largest left, so its final place is index 3. Swap it there.
5 is fixed (green). The heap shrinks to 3 items; the new root may break the rule.
Children of 1: 4 and 3. The larger child 4 beats the parent, so swap them.
4 rose to index 0; 1 sank to index 1. Keep checking it.
1 has no children inside the heap, so sift-down stops.
4 is the largest left, so its final place is index 2. Swap it there.
4 is fixed (green). The heap shrinks to 2 items; the new root may break the rule.
Children of 3: 1. Neither beats it, so the rule holds and sift-down stops.
3 is the largest left, so its final place is index 1. Swap it there.
3 is fixed (green). The heap shrinks to 1 item; the new root may break the rule.
One item left, so it is in place too:
[1, 3, 4, 5, 7, 8, 10]. $n-1$ rounds of $O(\log n)$ give $O(n\log n)$.
Worked example: One round of heap sort
Problem.
Max-heap [10, 5, 8, 1, 4]: do the first round.
Idea.
Swap root with last, shrink, sift down.
- Swap index 0 and 4:
[4, 5, 8, 1, 10]; 10 is final. - Heap part
[4, 5, 8, 1]: children of 4 are 5 and 8, larger is 8: swap:[8, 5, 4, 1, 10].
Answer.
[8, 5, 4, 1, 10]
Common mistake.
Forgetting that 10 is no longer part of the heap.
Worked example: Index arithmetic
Problem.
A heap has 120 elements, 0-indexed. Index of the right child of the node at index 59? Does it exist?
Idea.
$2i+2$.
- $2\cdot59+2=120$.
- The last index is $119$, so index 120 does not exist. The left child, $2\cdot59+1=119$, does.
Answer.
120, so there is no right child
Common mistake.
Using $2i+1$ or a 1-indexed formula.
| Common mistake | Correction |
|---|---|
| saying build-heap is $O(n\log n)$ | it is $O(n)$ (a loop of $n$ separate inserts would be $O(n\log n)$) |
| saying heap sort has a best case $O(n)$ | no: always $n\log n$ |
| saying heap sort is stable | it is not |
| starting build-heap at index $n-1$ | start at $\lfloor n/2\rfloor-1$ |
Mnemonic "BUILD then DRAIN": build a max-heap in $O(n)$, then drain it $n$ times at $O(\log n)$ each.
Worked example: The wrong kind of heap
Problem.
Heap sort's swap-and-shrink steps are run with a min-heap on $3,1,2$, filling the array from the end. What order results?
Idea.
Each step places the current top at the end of the unsorted part.
- The minimum 1 goes to the last place.
- Then 2 goes before it.
- Then 3 goes first.
Answer.
$[3,2,1]$: decreasing order.
Common mistake.
Expecting increasing order from a min-heap.
Build, swap, shrink.
| Step | Method for any exam question |
|---|---|
| 1 | Build a max-heap from the last parent backwards. |
| 2 | Swap the root with the end. |
| 3 | Shrink the heap and sift down. |