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?