Proofs: Calendar queue
These are the human proofs of Calendar queue, at full length.
The calendar queue returns an event of smallest time full
This proof shows: correctness, termination.
Let for the current width . Since is non-decreasing for , and so is the floor, is non-decreasing: implies , and so implies . Events are compared by the pair (time, arrival number), and depends on the time only.
Invariants. Between operations, with events in the queue:
(B) each event with time is in the bucket , exactly once, and each bucket is sorted by (time, arrival);
(V) if , then for each event in the queue.
Both hold for the empty queue.
Lemma 1. Let (B) and (V) hold with . If is not empty and its first event has , then is a smallest event of the queue. Else no event has the virtual bucket , and (V) holds with .
Proof. Let be any event. If , then has a larger time than . Else by (V), so is in the same bucket by (B), and comes first in that sorted bucket, so . For the second part: if some event had , the bucket would not be empty, and its first event would satisfy , since in the bucket and is non-decreasing. So all events have .
INSERT. Line L2 puts the event into the bucket of (B) at its sorted place, so (B) holds. If the queue was empty, line L3 sets and (V) holds for the one event. Else (V) held for the old events, and line L3 lowers if needed, so it holds for the new one too, and lowering keeps it for the old ones.
EXTRACT-MIN. Let . By Lemma 1, each iteration of the loop of lines L6 to L10 either finds a smallest event, removes it, and returns it, or moves up by one and keeps (V). The loop runs at most times. If it finds no event, line L11 compares the first events of all buckets; by (B), the first event of each bucket is its smallest, so the result is a smallest event of the queue. Line L12 sets for this smallest ; every event has a time at least , so , and (V) holds. Removing the first event of a bucket keeps (B), and removing any event keeps (V).
RESIZE. It takes all events out, picks a new width and a new , puts each event into and sorts each bucket, so (B) holds for the new . It sets to the least , so (V) holds. Lemma 1 holds for any width, so the next operations are correct.
Theorem. Each operation stops, after at most iterations of the scan plus one direct search and one resize. Each EXTRACT-MIN on a non-empty queue returns a smallest event, and events with equal times leave in the order of arrival.
Proof. Termination is the bound on the loop. The answer is a smallest pair (time, arrival) by Lemma 1 and the analysis of the direct search, which gives the second claim.