Lesson contents

Heaps and priority queues

A min-heap keeps the smallest priority at its root. When a smaller item arrives, move it up until the parent is no larger.

Simple example

Start with a min-heap containing 4, 8 and 6. Insert 2, move it past 8 and 4, then print the root.

Start4 8 6
Result2
lesson.zig
const std = @import("std");

fn show(value: i64) !void {
    var buffer: [64]u8 = undefined;
    var writer = std.fs.File.stdout().writer(&buffer);
    try writer.interface.print("{d}\n", .{value});
    try writer.interface.flush();
}

pub fn main() !void {
    var heap = [_]i64{4, 8, 6, 0};
    var child: i64 = 3;
    heap[@intCast(child)] = 2;
    while (child > 0) {
        const parent: i64 = @divFloor((child - 1), 2);
        if (heap[@intCast(parent)] <= heap[@intCast(child)]) {
            break;
        }
        const saved: i64 = heap[@intCast(parent)];
        heap[@intCast(parent)] = heap[@intCast(child)];
        heap[@intCast(child)] = saved;
        child = parent;
    }
    try show(heap[0]);
}
Output
2
Advertisements

Everyday examples

Sound the next timer

Timers are set for minutes 12, 5 and 9. Which one should ring first?

Start12 5 9
Result5

Keep a min-heap of times. Its root is the earliest timer even if it was entered later.

Dispatch the nearest deadline

Parcel deadlines are at hours 16, 18 and 20. A parcel due at 14 arrives. Which goes next?

Start16 18 20 14
Result14

Insert the new deadline and move it towards the root. The earlier deadline takes priority.

Keep equal priorities fair

Orders A and B both have priority 2. A arrived first. How can the queue break the tie?

Start2,A 2,B
ResultA

Compare priority first and arrival sequence second. A heap alone does not promise arrival order for ties.

Cost and limits

Reading the root takes constant time. Insertion and removing the root take logarithmic time. The remaining values are only partly ordered.