Heaps and Priority Queues

A heap gives the smallest or largest item fast. Greedy algorithms and shortest paths lean on it.

5 lessons · 19 past questions · 59 marks in the papers collected here

Open the interactive lessons →Heaps and Priority Queues past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. What a heap is: shape, rule and the array
  2. Insertion: put it at the end, then sift up
  3. Deleting the root: move the last up, then sift down
  4. Where can the largest, smallest or k-th element be?
  5. 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 wordMeaning
complete treelevels filled from left to right with no gaps
heap orderevery parent is at least as good as its children
indexthe 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.

Definition

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.

Not sorted

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:

Index formulas

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$valueparent $\lfloor(i-1)/2\rfloor$left $2i+1$right $2i+2$
02-12
15034
210056
315178
471--
5202--
6252--
7183--
8193--
Convention

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)FormulaExample $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
leavesindices $\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 and its limit

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-heapMax-heapBSTSorted array
order ruleparent $\le$ childrenparent $\ge$ childrenleft < node < right$a_i\le a_{i+1}$
shapecompletecompleteanyn/a
stored asarrayarraylinked nodesarray
minimumroot, $O(1)$a leaf, $O(n)$leftmost, $O(h)$first, $O(1)$
maximuma 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?nonoyesyes
Common mistakeCorrection
reading a heap array as sortedonly parent-child pairs are ordered
using $2i$ and $2i+1$ in a 0-indexed arrayuse $2i+1$ and $2i+2$
placing a new node anywherealways the first free slot (next index)
thinking the max of a min-heap is the last elementit 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.

  1. Index 0 (3): children 8, 5: ok.
  2. Index 1 (8): children 10, 9 (indices 3, 4): ok.
  3. Index 2 (5): children 6, 7 (indices 5, 6): ok.
  4. 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.

  1. Index 7 holds 7. Its parent is index $\lfloor 6/2\rfloor=3$, which holds 9.
  2. 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. 1 is not greater than 5 or 2.
  2. 5 is not greater than 9 or 6.
  3. 2 is not greater than 3.

Answer.

Yes, although the list is not sorted.

Common mistake.

Rejecting it because 5 comes before 2.

Tips and tricks
  • 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$.
Memory line

Children of i are at 2i+1 and 2i+2.

StepMethod for any exam question
1Check the shape: no gaps.
2Find children and parent by index.
3Check 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 wordMeaning
sift upswap with the parent while out of order
last positionthe next free slot of the array
path to the rootthe only nodes an insertion can move
Picture it

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]

  1. A valid min-heap [5, 8, 11, 15, 20]. We will insert 3.

  2. Put 3 in the first empty slot, index 5, so the tree stays complete. Only this spot can break the heap rule.

  3. The child 3 is smaller than its parent 11 (index 2), so the min-heap rule is broken: swap.

  4. 3 moved up to index 2. Check it against its new parent.

  5. The child 3 is smaller than its parent 5 (index 0), so the min-heap rule is broken: swap.

  6. 3 moved up to index 0. Check it against its new parent.

  7. Heap restored: [3, 8, 5, 15, 20, 11]. The new value reached the root.

CaseSwapsCost
new value $\ge$ its parent0$O(1)$ (best)
new value is the new minimum$h-1$ (up to the root)$O(\log n)$ (worst)
average for random dataabout 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

steparrayaction
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.

  1. Array [2, 6, 5, 9, 8, 4], new index 5.
  2. Parent index 2 (value 5): 4 < 5, swap: [2, 6, 4, 9, 8, 5].
  3. 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.

  1. Append: [40, 30, 35, 10, 20, 50], index 5.
  2. Parent index 2 (35): 50 > 35 swap: [40, 30, 50, 10, 20, 35].
  3. 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.

Reverse thinking

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 mistakeCorrection
inserting at the rootalways at index $n$
swapping with the smaller siblingcompare only with the parent
continuing after the rule holdsstop 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.

  1. Inserting: $[3]$, then $[2,3]$, then $[1,3,2]$.
  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.

Memory line

End, then up.

StepMethod for any exam question
1Put it at the end.
2Compare with the parent.
3Swap 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 wordMeaning
rootthe smallest (or largest) item
sift downswap with the better child while out of order
better childthe smaller one in a min-heap, the larger in a max-heap
Picture it

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
Which child?

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]

  1. A valid min-heap. delete_min must return the root 3.

  2. The root leaves a hole. We fill it with the last element, 20, so no gap appears in the array.

  3. The array shrinks to 8 items. The shape is complete, but the new root may be too big.

  4. Children of 20: 7 and 11. The smaller child 7 beats the parent, so swap them.

  5. 7 rose to index 0; 20 sank to index 1. Keep checking it.

  6. Children of 20: 16 and 9. The smaller child 9 beats the parent, so swap them.

  7. 9 rose to index 1; 20 sank to index 4. Keep checking it.

  8. 20 has no children inside the heap, so sift-down stops.

  9. 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].

OperationMin-heap timeWhy
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.

  1. Move 4 to the root: [4, 3, 2, 7].
  2. Children of 4: 3 and 2. Smaller is 2: swap: [2, 3, 4, 7].
  3. 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.

  1. delete_min: the last item 70 moves to the root and sinks, swapping with the smaller child each time.
  2. After the delete: [9, 41, 25, 60, 70, 31, 27].
  3. 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 mistakeCorrection
moving the smaller child up and leaving a gapalways move the last element to the root
swapping with the larger child in a min-heapsmaller child
forgetting to pop the last slotthe array must shrink by one
sifting down when the children do not exista 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.

  1. Move 3 to the root: $[3,5,2,9,6]$.
  2. The children are 5 and 2; swap with 2.
  3. 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.

Tips and tricks
  • 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.
Memory line

Last to the top, then down.

StepMethod for any exam question
1Remove the root.
2Move the last item there.
3Swap 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 wordMeaning
second bestalways a child of the root
leaf rangeindices $\lfloor n/2\rfloor$ to $n-1$
k-th elementcan be at depth at most $k-1$
Picture it

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 valuesTrue?Reason
the largest is at a leaftruean internal node has a larger child
the largest is at the lowest levelfalsemay be a leaf on the level above
the second smallest is a child of the roottrueFact 2
finding the largest takes $O(\log n)$falseneeds scanning all leaves: $O(n)$
inserting takes $O(\log n)$truesift-up
deleting the minimum takes $O(1)$falsesift-down is $O(\log n)$
update the value at a known index is $O(\log n)$trueone 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 rangeall 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, leavesyes
A[45] to A[59]no, leavesyes

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$.

  1. $\lfloor10/2\rfloor=5$, so indices 5 to 9 are leaves.
  2. 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.

  1. After removing the root the next largest must be the top of a subtree, so one of the two children of the root.
  2. True.

Answer.

true

Common mistake.

Believing the third largest is also always a child of the root: it can be a grandchild.

Common mistakeCorrection
"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)$
Memory trick

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. 1 is above 2 and 5; 2 is above 3.
  2. The third smallest is 3, at index 3.
  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.

Memory line

Second best touches the root; the opposite extreme is a leaf.

StepMethod for any exam question
1Use the parent rule to narrow the positions.
2Check 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 wordMeaning
heapifyturning an array into a heap from the bottom up
in placeusing only constant extra memory
stableequal items keep their original order
Picture it

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]

  1. This array is not a heap yet. Leaves are already tiny heaps, so we begin at the last internal node, index 2.

  2. Both subtrees under index 2 are max-heaps. Now push 3 down to where it belongs.

  3. Children of 3: 8 and 7. The larger child 8 beats the parent, so swap them.

  4. 8 rose to index 2; 3 sank to index 5. Keep checking it.

  5. 3 has no children inside the heap, so sift-down stops.

  6. Both subtrees under index 1 are max-heaps. Now push 10 down to where it belongs.

  7. Children of 10: 5 and 1. Neither beats it, so the rule holds and sift-down stops.

  8. Both subtrees under index 0 are max-heaps. Now push 4 down to where it belongs.

  9. Children of 4: 10 and 8. The larger child 10 beats the parent, so swap them.

  10. 10 rose to index 0; 4 sank to index 1. Keep checking it.

  11. Children of 4: 5 and 1. The larger child 5 beats the parent, so swap them.

  12. 5 rose to index 1; 4 sank to index 3. Keep checking it.

  13. 4 has no children inside the heap, so sift-down stops.

  14. 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]

stepheap partsorted 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.

Stability

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.

PropertyHeap sortMerge sortQuick 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?noyesno
depends on input order?nonoyes
Heap sort statementTrue?Reason
$O(n\log n)$ irrespective of the inputtrueno best case shortcut
$O(n^2)$ worst, $O(n\log n)$ bestfalseworst is also $n\log n$
in-placetrueswaps inside the array
not stabletruethe long-distance swap

After build-heap the max is at the root

steparrayheap 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]

  1. A max-heap: the largest value 10 is at the root. The sorted part on the right is still empty.

  2. 10 is the largest left, so its final place is index 6. Swap it there.

  3. 10 is fixed (green). The heap shrinks to 6 items; the new root may break the rule.

  4. Children of 7: 5 and 8. The larger child 8 beats the parent, so swap them.

  5. 8 rose to index 0; 7 sank to index 2. Keep checking it.

  6. Children of 7: 3. Neither beats it, so the rule holds and sift-down stops.

  7. 8 is the largest left, so its final place is index 5. Swap it there.

  8. 8 is fixed (green). The heap shrinks to 5 items; the new root may break the rule.

  9. Children of 3: 5 and 7. The larger child 7 beats the parent, so swap them.

  10. 7 rose to index 0; 3 sank to index 2. Keep checking it.

  11. 3 has no children inside the heap, so sift-down stops.

  12. 7 is the largest left, so its final place is index 4. Swap it there.

  13. 7 is fixed (green). The heap shrinks to 4 items; the new root may break the rule.

  14. Children of 1: 5 and 3. The larger child 5 beats the parent, so swap them.

  15. 5 rose to index 0; 1 sank to index 1. Keep checking it.

  16. Children of 1: 4. The larger child 4 beats the parent, so swap them.

  17. 4 rose to index 1; 1 sank to index 3. Keep checking it.

  18. 1 has no children inside the heap, so sift-down stops.

  19. 5 is the largest left, so its final place is index 3. Swap it there.

  20. 5 is fixed (green). The heap shrinks to 3 items; the new root may break the rule.

  21. Children of 1: 4 and 3. The larger child 4 beats the parent, so swap them.

  22. 4 rose to index 0; 1 sank to index 1. Keep checking it.

  23. 1 has no children inside the heap, so sift-down stops.

  24. 4 is the largest left, so its final place is index 2. Swap it there.

  25. 4 is fixed (green). The heap shrinks to 2 items; the new root may break the rule.

  26. Children of 3: 1. Neither beats it, so the rule holds and sift-down stops.

  27. 3 is the largest left, so its final place is index 1. Swap it there.

  28. 3 is fixed (green). The heap shrinks to 1 item; the new root may break the rule.

  29. 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.

  1. Swap index 0 and 4: [4, 5, 8, 1, 10]; 10 is final.
  2. 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$.

  1. $2\cdot59+2=120$.
  2. 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 mistakeCorrection
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 stableit is not
starting build-heap at index $n-1$start at $\lfloor n/2\rfloor-1$
Memory trick

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.

  1. The minimum 1 goes to the last place.
  2. Then 2 goes before it.
  3. Then 3 goes first.

Answer.

$[3,2,1]$: decreasing order.

Common mistake.

Expecting increasing order from a min-heap.

Memory line

Build, swap, shrink.

StepMethod for any exam question
1Build a max-heap from the last parent backwards.
2Swap the root with the end.
3Shrink the heap and sift down.

Practise this topic →

Other PDSA topics