Advanced topics · Exercise 88 of 100
Priority queue
When smaller numbers take priority, a priority queue can use a min-heap that keeps the smallest number at the root. Insert an item at the end and swap it with its parent while its number is smaller. To remove the root, move the last remaining item into the gap if there is one, then swap it with its smaller child while that child has a smaller number.
Try it yourself
In a queue where smaller numbers take priority, add wax with priority 6 and ink with priority 2. Remove one item, then add clay with priority 4. Which item comes out next?
One-step hint
Write each item beside its priority. Cross out the smallest priority at the first removal, then compare the surviving priority with the new arrival's.
Worked solution
- The first removal takes ink because 2 is smaller than 6, leaving wax in the queue.
- After clay arrives, its priority of 4 beats wax's 6, so the next removal takes clay.