Heaps and priority queues
The priority queue interface, why search trees are more than it needs, binary min-heaps with swim and sink, storing a complete tree in an array, a generic heap with a comparator, and heapify in linear time.
- CS61B
- Heaps, Priority Queues, and Tree Representations · Textbook Ch. 18
- Swift book
- Generics
- Documentation
- Swift Collections
Many programs do not need everything in order: they need the smallest thing, again and again. An emergency room treats the most urgent patient next; a scheduler runs the task due soonest; Dijkstra’s shortest-path algorithm, in Lesson 45, always explores the closest unexplored place. This lesson, like CS61B’s, builds the structure for that, and along the way shows a second way to store a tree: in an array, with no references at all.
The priority queue
A priority queue supports three operations:
add(item): insert an item.min: look at the smallest item.removeMin(): remove and return the smallest item.
A sorted array makes min instant, but add linear. An unsorted array makes
add instant, but min linear. A balanced search tree does everything in
Θ(log N), but keeps a complete order that nobody asked for. A heap keeps
just enough order: Θ(log N) for add and removeMin, Θ(1) for min, and it is
simpler and faster than a search tree in practice.
Binary min-heaps
A binary min-heap is a binary tree with two properties:
- Min-heap order: every node is less than or equal to its children. So the smallest item is at the root. Unlike a search tree, nothing is said about left versus right.
- Completeness: every level is full, except possibly the last, which is filled from the left. So the tree’s height is always ⌊log₂ N⌋.
1
/ \
3 2
/ \ /
7 4 5
Adding puts the new item in the next free position, which keeps the tree complete, and then lets it swim up: while it is smaller than its parent, swap them. At most one swap per level, so Θ(log N).
Removing the minimum takes the root, moves the last item to the root, which again keeps the tree complete, and lets it sink: while it is larger than one of its children, swap it with the smaller child. Swapping with the smaller keeps the order property for the other child. Again Θ(log N).
A tree in an array
A complete tree has no gaps, so it fits in an array perfectly: store the nodes
level by level, left to right. Then, for the node at index i:
- its left child is at
2i + 1, - its right child is at
2i + 2, - its parent is at
(i − 1) / 2.
index: 0 1 2 3 4 5
item: 1 3 2 7 4 5
No child references, no nodes, and every item is next to its neighbors in
memory, which Lesson 30 showed matters. CS61B also describes a version that
leaves index 0 empty so the formulas become 2i, 2i + 1, and i / 2; the
two are equivalent.
struct MinHeap<Element: Comparable> {
private var items: [Element] = []
var count: Int { items.count }
var min: Element? { items.first }
mutating func add(_ item: Element) {
items.append(item)
swim(items.count - 1)
}
mutating func removeMin() -> Element? {
guard !items.isEmpty else { return nil }
items.swapAt(0, items.count - 1)
let smallest = items.removeLast()
sink(0)
return smallest
}
private mutating func swim(_ i: Int) {
var i = i
while i > 0 {
let parent = (i - 1) / 2
guard items[i] < items[parent] else { break }
items.swapAt(i, parent)
i = parent
}
}
private mutating func sink(_ i: Int) {
var i = i
while true {
let left = 2 * i + 1
let right = left + 1
var smallest = i
if left < items.count && items[left] < items[smallest] { smallest = left }
if right < items.count && items[right] < items[smallest] { smallest = right }
guard smallest != i else { break }
items.swapAt(i, smallest)
i = smallest
}
}
}
var heap = MinHeap<Int>()
for n in [5, 3, 8, 1, 9, 2] {
heap.add(n)
}
var out: [Int] = []
while let n = heap.removeMin() {
out.append(n)
}
print(out) // [1, 2, 3, 5, 8, 9]
Removing everything from a heap produces the items in sorted order: that is heap sort, which Lesson 54 examines. Here the heap uses a Swift array, which grows by itself, so the fixed-size bookkeeping of Lesson 30 is not needed.
What would Swift print?
var items = [1, 3, 2, 7, 4, 5]
items.append(0)
var i = items.count - 1
var swaps = 0
while i > 0 && items[i] < items[(i - 1) / 2] {
items.swapAt(i, (i - 1) / 2)
i = (i - 1) / 2
swaps += 1
}
print(items, swaps)Show answer and explanation
Answer[0, 3, 1, 7, 4, 5, 2] 2
0 goes in position 6, whose parent is position 2 (holding 2). It swaps up to position 2, then with the root: two swaps, the height of the tree. The rest of the array is untouched.
Any order: comparators
A heap of numbers orders them by <. Real priority queues order tasks by
deadline, patients by urgency, or paths by length. As in Lesson 32, the heap
can take a comparator, a function saying which of two items comes first, and
work for any type:
struct Heap<Element> {
private var items: [Element] = []
private let areInOrder: (Element, Element) -> Bool
init(by areInOrder: @escaping (Element, Element) -> Bool) {
self.areInOrder = areInOrder
}
var count: Int { items.count }
var peek: Element? { items.first }
mutating func insert(_ item: Element) {
items.append(item)
var i = items.count - 1
while i > 0, areInOrder(items[i], items[(i - 1) / 2]) {
items.swapAt(i, (i - 1) / 2)
i = (i - 1) / 2
}
}
mutating func pop() -> Element? {
guard !items.isEmpty else { return nil }
items.swapAt(0, items.count - 1)
let top = items.removeLast()
var i = 0
while true {
let (left, right) = (2 * i + 1, 2 * i + 2)
var best = i
if left < items.count, areInOrder(items[left], items[best]) { best = left }
if right < items.count, areInOrder(items[right], items[best]) { best = right }
guard best != i else { break }
items.swapAt(i, best)
i = best
}
return top
}
}
struct Task {
let name: String
let due: Int
}
var queue = Heap<Task> { $0.due < $1.due }
for task in [Task(name: "laundry", due: 5), Task(name: "taxes", due: 2), Task(name: "email", due: 3)] {
queue.insert(task)
}
var maxHeap = Heap<Int>(by: >)
for n in [4, 9, 1] {
maxHeap.insert(n)
}
print(queue.pop()!.name, queue.pop()!.name, maxHeap.pop()!) // taxes email 9
Passing > gives a max-heap. The Swift Collections package has a
production-quality Heap type, a min-max heap that can remove from either end.
Building a heap in linear time
Adding N items one at a time takes Θ(N log N). If all the items are available at once, there is a faster way, heapify: put them in the array in any order, then sink every node that has children, from the last one back to the root.
var comparisons = 0
func heapify(_ items: inout [Int]) {
func sink(_ i: Int) {
var i = i
while true {
let (left, right) = (2 * i + 1, 2 * i + 2)
var smallest = i
if left < items.count { comparisons += 1; if items[left] < items[smallest] { smallest = left } }
if right < items.count { comparisons += 1; if items[right] < items[smallest] { smallest = right } }
guard smallest != i else { return }
items.swapAt(i, smallest)
i = smallest
}
}
for i in stride(from: items.count / 2 - 1, through: 0, by: -1) {
sink(i)
}
}
var items = Array((0..<100_000).reversed()) // the worst order for a min-heap
heapify(&items)
print(items[0], comparisons < 2 * 2 * items.count) // 0 true
Most nodes are near the bottom, where sinking is cheap: half the nodes are leaves and do nothing, a quarter sink at most one level, an eighth at most two, and so on. The total is N/4 · 1 + N/8 · 2 + N/16 · 3 + …, which is less than N: heapify is Θ(N). The count here is well under four comparisons per item.
Put the lines in order
Put the lines in order so the program prints 6 1.
let items = [1, 3, 2, 7, 4, 5, 6]let (right, root) = (items[2 * i + 2], items[(i - 1) / 2])print(right, root)let i = 2
Show the correct program
let items = [1, 3, 2, 7, 4, 5, 6]
let i = 2
let (right, root) = (items[2 * i + 2], items[(i - 1) / 2])
print(right, root)Lab 40: Heaps
Q0: What would Swift print?
What would Swift print?
var items = [1, 3, 2, 7, 4, 5]
items.swapAt(0, items.count - 1)
let removed = items.removeLast()
var i = 0
while true {
let l = 2 * i + 1, r = 2 * i + 2
var s = i
if l < items.count && items[l] < items[s] { s = l }
if r < items.count && items[r] < items[s] { s = r }
if s == i { break }
items.swapAt(i, s)
i = s
}
print(removed, items)Show answer and explanation
Answer1 [2, 3, 5, 7, 4]
5 moves to the root and sinks: its children are 3 and 2, and it swaps with the smaller, 2. At position 2, it has no children left, so it stops.
Q1: Is it a heap?
Write isMinHeap(_:), which checks the heap property of an array in linear
time, and use it to check MinHeap after every operation of a randomized test.
Show solution
func isMinHeap(_ items: [Int]) -> Bool {
items.indices.dropFirst().allSatisfy { items[($0 - 1) / 2] <= items[$0] }
}
struct MinHeap {
private(set) var items: [Int] = []
mutating func add(_ item: Int) {
items.append(item)
var i = items.count - 1
while i > 0 && items[i] < items[(i - 1) / 2] {
items.swapAt(i, (i - 1) / 2)
i = (i - 1) / 2
}
}
mutating func removeMin() -> Int? {
guard !items.isEmpty else { return nil }
items.swapAt(0, items.count - 1)
let smallest = items.removeLast()
var i = 0
while true {
let (l, r) = (2 * i + 1, 2 * i + 2)
var s = i
if l < items.count && items[l] < items[s] { s = l }
if r < items.count && items[r] < items[s] { s = r }
guard s != i else { break }
items.swapAt(i, s)
i = s
}
return smallest
}
}
var heap = MinHeap()
var reference: [Int] = []
var generator = SystemRandomNumberGenerator()
for _ in 0..<5_000 {
if Int.random(in: 0..<3, using: &generator) < 2 {
let n = Int.random(in: 0..<100, using: &generator)
heap.add(n)
reference.append(n)
} else {
let expected = reference.min()
if let m = expected { reference.remove(at: reference.firstIndex(of: m)!) }
assert(heap.removeMin() == expected)
}
assert(isMinHeap(heap.items))
}Checking each node against its parent covers every parent–child pair exactly
once. The reference is a plain array whose min() is linear: slow, but
obviously correct, which is what a reference should be.
Q2: The k smallest
Write smallest(_:k:), which returns the k smallest items of a large array in
sorted order, in O(N log k) time, by keeping a max-heap of the best k seen
so far.
Show solution
struct Heap<Element> {
private(set) var items: [Element] = []
let areInOrder: (Element, Element) -> Bool
var count: Int { items.count }
var peek: Element? { items.first }
mutating func insert(_ item: Element) {
items.append(item)
var i = items.count - 1
while i > 0, areInOrder(items[i], items[(i - 1) / 2]) {
items.swapAt(i, (i - 1) / 2)
i = (i - 1) / 2
}
}
mutating func pop() -> Element? {
guard !items.isEmpty else { return nil }
items.swapAt(0, items.count - 1)
let top = items.removeLast()
var i = 0
while true {
let (l, r) = (2 * i + 1, 2 * i + 2)
var best = i
if l < items.count, areInOrder(items[l], items[best]) { best = l }
if r < items.count, areInOrder(items[r], items[best]) { best = r }
guard best != i else { break }
items.swapAt(i, best)
i = best
}
return top
}
}
func smallest(_ values: [Int], k: Int) -> [Int] {
var best = Heap<Int>(areInOrder: >) // the largest of the best k on top
for value in values {
if best.count < k {
best.insert(value)
} else if let largest = best.peek, value < largest {
_ = best.pop()
best.insert(value)
}
}
var result: [Int] = []
while let value = best.pop() {
result.append(value)
}
return result.reversed()
}
let values = (0..<100_000).map { ($0 * 7919) % 100_000 }
assert(smallest(values, k: 5) == [0, 1, 2, 3, 4])
assert(smallest([5, 1, 4], k: 10) == [1, 4, 5])The heap never holds more than k items, so each operation is O(log k), not
O(log N). The max-heap’s top is the worst of the best k, exactly the one to
compare each new value with. For k = 5, the work is essentially linear, and far
less memory than sorting a copy.
Q3: Merging sorted lists
Write mergeSorted(_:), which merges k sorted arrays into one sorted array in
O(N log k) time, using a min-heap of (value, list, position) entries, one per
list.
Show solution
struct Heap<Element> {
private var items: [Element] = []
let areInOrder: (Element, Element) -> Bool
mutating func insert(_ item: Element) {
items.append(item)
var i = items.count - 1
while i > 0, areInOrder(items[i], items[(i - 1) / 2]) {
items.swapAt(i, (i - 1) / 2)
i = (i - 1) / 2
}
}
mutating func pop() -> Element? {
guard !items.isEmpty else { return nil }
items.swapAt(0, items.count - 1)
let top = items.removeLast()
var i = 0
while true {
let (l, r) = (2 * i + 1, 2 * i + 2)
var best = i
if l < items.count, areInOrder(items[l], items[best]) { best = l }
if r < items.count, areInOrder(items[r], items[best]) { best = r }
guard best != i else { break }
items.swapAt(i, best)
i = best
}
return top
}
}
func mergeSorted(_ lists: [[Int]]) -> [Int] {
typealias Entry = (value: Int, list: Int, position: Int)
var heap = Heap<Entry> { $0.value < $1.value }
for (list, values) in lists.enumerated() where !values.isEmpty {
heap.insert((values[0], list, 0))
}
var result: [Int] = []
while let entry = heap.pop() {
result.append(entry.value)
let next = entry.position + 1
if next < lists[entry.list].count {
heap.insert((lists[entry.list][next], entry.list, next))
}
}
return result
}
assert(mergeSorted([[1, 4, 9], [2, 3], [], [0, 10]]) == [0, 1, 2, 3, 4, 9, 10])
assert(mergeSorted([]) == [])The heap holds one entry per list, the smallest item not yet taken from it. Taking the heap’s minimum and replacing it with the next item from the same list keeps that true. Databases and search engines merge sorted runs of data this way.
Q4: Heapify, counted
Show that heapify is linear by counting swaps for arrays of 2¹⁰ to 2¹⁶ items in the worst order, and checking that the number of swaps per item stays below a constant, while adding the items one at a time does not.
Show solution
func heapifySwaps(_ n: Int) -> Int {
var items = Array((0..<n).reversed())
var swaps = 0
for start in stride(from: n / 2 - 1, through: 0, by: -1) {
var i = start
while true {
let (l, r) = (2 * i + 1, 2 * i + 2)
var s = i
if l < n && items[l] < items[s] { s = l }
if r < n && items[r] < items[s] { s = r }
guard s != i else { break }
items.swapAt(i, s)
swaps += 1
i = s
}
}
return swaps
}
func insertionSwaps(_ n: Int) -> Int {
var items: [Int] = []
var swaps = 0
for value in (0..<n).reversed() {
items.append(value)
var i = items.count - 1
while i > 0 && items[i] < items[(i - 1) / 2] {
items.swapAt(i, (i - 1) / 2)
swaps += 1
i = (i - 1) / 2
}
}
return swaps
}
for k in 10...16 {
let n = 1 << k
assert(Double(heapifySwaps(n)) / Double(n) < 1)
}
assert(Double(insertionSwaps(1 << 16)) / Double(1 << 16) > 10)For heapify, swaps per item stay below one at every size. Inserting a decreasing sequence one at a time makes every new item swim all the way to the root, so swaps per item grow like log₂ N, about 14 at 2¹⁶.
Q5 (optional): A median tracker
Keep the running median of a stream of numbers, with each insertion in O(log N): keep the smaller half in a max-heap and the larger half in a min-heap, with sizes differing by at most one.
Show solution
struct Heap<Element> {
private(set) var items: [Element] = []
let areInOrder: (Element, Element) -> Bool
var count: Int { items.count }
var peek: Element? { items.first }
mutating func insert(_ item: Element) {
items.append(item)
var i = items.count - 1
while i > 0, areInOrder(items[i], items[(i - 1) / 2]) {
items.swapAt(i, (i - 1) / 2)
i = (i - 1) / 2
}
}
mutating func pop() -> Element? {
guard !items.isEmpty else { return nil }
items.swapAt(0, items.count - 1)
let top = items.removeLast()
var i = 0
while true {
let (l, r) = (2 * i + 1, 2 * i + 2)
var best = i
if l < items.count, areInOrder(items[l], items[best]) { best = l }
if r < items.count, areInOrder(items[r], items[best]) { best = r }
guard best != i else { break }
items.swapAt(i, best)
i = best
}
return top
}
}
struct MedianTracker {
private var lower = Heap<Int>(areInOrder: >) // max-heap: the smaller half
private var upper = Heap<Int>(areInOrder: <) // min-heap: the larger half
mutating func add(_ value: Int) {
if let top = lower.peek, value > top {
upper.insert(value)
} else {
lower.insert(value)
}
if lower.count > upper.count + 1 {
upper.insert(lower.pop()!)
} else if upper.count > lower.count {
lower.insert(upper.pop()!)
}
}
/// The lower median when the count is even.
var median: Int? { lower.peek }
}
var tracker = MedianTracker()
var medians: [Int] = []
for value in [5, 15, 1, 3, 8, 7, 9, 10] {
tracker.add(value)
medians.append(tracker.median!)
}
assert(medians == [5, 5, 5, 3, 5, 5, 7, 7])After each addition, every item in lower is at most every item in upper,
and lower has the same number of items or one more. So the median is always
lower’s top, found in constant time.
What’s next
That completes Unit 5’s trees. Unit 6 turns to graphs, starting with SwiftUI for the data-driven screens that Project 9 needs, and then traversals.