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.
object Lesson {
def main(args: Array[String]): Unit = {
var heap = Array(4, 8, 6, 0)
var child = 3
heap(child) = 2
scala.util.control.Breaks.breakable { while (child > 0) {
var parent = (child - 1) / 2
if (heap(parent) <= heap(child)) {
scala.util.control.Breaks.break()
}
var saved = heap(parent)
heap(parent) = heap(child)
heap(child) = saved
child = parent
} }
println(heap(0))
}
}
2
Everyday examples
Sound the next timer
Timers are set for minutes 12, 5 and 9. Which one should ring first?
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?
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?
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.