Learn / Heaps and priority queues

Heap implementation

A binary heap is a complete binary tree stored in an array: the children of index i are 2i + 1 and 2i + 2, and every parent is at most (min heap) or at least (max heap) its children. Insert adds at the end and sifts up; removing the top moves the last item to the top and sifts down. Both are O(log n), and building from n values bottom-up is O(n).

How to recognise it

  • You need the smallest or largest item again and again while items are added and removed.
  • The problem asks you to build, check, repair or convert a heap stored in an array.
  • Sorting in place with O(1) extra space and a guaranteed O(n log n).

The picture

132745
A min heap. Read level by level it is the array [1, 3, 2, 7, 4, 5].

As an array this heap is [1, 3, 2, 7, 4, 5]. Read the tree level by level, left to right, and you get the array. The general idea and the library calls are on the Structures page; this lesson is about writing one yourself.

RelationIndex
parent of i(i - 1) / 2
left child of i2i + 1
right child of i2i + 2
first leafn / 2

Because the tree is complete (every level full except the last, which fills from the left), the array has no gaps.

Sift up and sift down

  • Insert: put the value at the end, then swap it with its parent while it is smaller (for a min heap). Here is the heap above after inserting 0:
0317452
After inserting 0: it entered at the end, under 2, and rose past 2 and then 1. The highlighted nodes moved.
  • Remove the top: move the last item to index 0, then swap it with its smaller child while that child is smaller.
  • Change a key: set the value, then sift up if it got smaller or down if it got bigger. Only one of the two can move it.

Each sift walks one path from top to bottom, so it costs O(log n).

Building a heap in O(n)

Call sift-down on every non-leaf, from the last one (n / 2 - 1) back to the root. Most nodes are near the bottom and sink only a step or two, which adds up to O(n), better than n inserts at O(n log n).

Heap sort

Build a max heap. Then swap the top (the maximum) with the last slot, shrink the heap by one and sift the new top down. Repeat. The array ends sorted ascending, in O(n log n) time and O(1) extra space. It is not stable.

Common mistakes

  • Using 2i and 2i + 1 (that is the 1-based layout) with a 0-based array.
  • Sifting down with the wrong child: in a min heap always pick the smaller one.
  • Forgetting that sibling order is free: a heap is not sorted, and many arrays are valid heaps of the same values.

Problems

0 of 10 solved

Check yourself

In an array heap, where are the children of index 3?

After removing the top of a min heap, which item goes into the empty top slot?

Why does bottom-up heap building start at index n / 2 - 1?

Is the array [1, 5, 2, 6, 3] a min heap?