All episodes · From a List to Your Map App · Episode 14

Who Goes First? Heaps and Priority Queues

Pressing play loads the video from YouTube.

Some lines aren't first come, first served: the most urgent job should go first. A heap keeps the most urgent item on top, always.
We see what a heap looks like as a tree and as an array at the same time, watch a new number swim up and the last one sink down (about log n swaps either way), use it as a priority queue, the tool operating systems and map apps rely on, and finish with heap sort, which sorts in place with no extra space.

Every animation in this video is drawn by code, and the narration is an AI voice.

Transcript

Some lines aren't first come, first served. The most urgent job should go first. A heap keeps the most urgent item on top, always, and adding or removing one takes just a few steps. Today: heaps and priority queues.

A heap is a tree with one rule: every parent is bigger than its children. So the biggest number is always at the top. It's filled row by row with no gaps, so it fits neatly in an array, just like in episode eleven. Tree on top, array below: the same numbers, linked by simple arithmetic.

To add a number, put it in the next empty spot at the end, then let it swim up. While it's bigger than its parent, swap them. Here, nine climbs past two, five and eight, all the way to the top. A heap of a million numbers is only twenty rows tall, so this takes about twenty swaps at most.

To take the top, move the last number into its place, then let it sink down. Swap it with its bigger child, again and again, until no child is bigger.

That's a priority queue. Tasks come in any order, but the most urgent one always comes out next. Operating systems use one to pick which program runs next, and map apps use one to pick which road to explore next.

Keep taking the top, and the numbers come out biggest first. Swap each one to the end, and the array fills up, sorted, from the back. That's heap sort: n log n steps, and no extra space at all.

A heap keeps the biggest on top, and adding or taking one costs about log n steps. That's all a priority queue needs. Next time: always grab whatever looks best right now. When does that greedy idea actually work? See you there.

Next episode: greedy algorithms. Grab whatever looks best right now, but when does that actually work?

Buy the Developer a Coffee

Entirely up to you: it works the same either way.

Every cup turns into the next update.

WeChat Pay QR code
WeChat Pay
Alipay QR code
Alipay
PayPal QR code
PayPal