Proofs: Bucket queue
These are the human proofs of Bucket queue, at full length.
The bucket queue returns an item of smallest key full
This proof shows: correctness, termination.
Let be the set of items in the queue, and for let be its key. The queue is correct if EXTRACT-MIN returns some with , removes it, and the other operations change and the keys as their names say.
Invariants. Between operations:
(B) for each , the bucket holds exactly the items with , and each item at most once;
(C) , and is empty for each .
Initially is empty, every bucket is empty, and , so (B) and (C) hold.
INSERT with and . Line L2 adds to with key and appends it to only, so (B) holds. If , the only bucket that changed has index at least , so (C) holds. Else line L3 sets ; the buckets below were below the old cursor and are empty, so (C) holds.
DELETE with . By (B), is in and nowhere else. Line L4 removes it from that bucket and from , so (B) holds. A bucket only lost an item, so (C) holds.
DECREASE-KEY with is a DELETE followed by an INSERT of the same item with key , so both invariants hold, and afterwards .
EXTRACT-MIN. Let be non-empty, and let . By (B), is non-empty, and by (C), , so .
The loop of line L8. Claim: before each test, and is empty for each . It holds before the first test, as shown. If the test is true, is empty, so and ; after the increment, and is empty for each below the new cursor. Each iteration raises by one and stays true, so the loop stops after at most iterations, and it never reads a bucket beyond .
When it stops, is non-empty, so by (B) some item has key , hence , and with the claim, . Line L9 takes an item of , so , and line L10 deletes it. Line L11 returns . The loop kept (C), and DELETE keeps (B) and (C).
FIND-MIN is the same without line L10, and it changes only the cursor, which keeps (C).
Theorem. Each sequence of operations on a bucket queue with keys in stops, and each EXTRACT-MIN or FIND-MIN on a non-empty queue returns an item of smallest key and that key. Items with equal keys come out in the order in which they last entered their bucket.
Proof. Each operation other than EXTRACT-MIN and FIND-MIN is straight-line code, and their loop stops, as shown. The first claim is the analysis of EXTRACT-MIN above. For the last, each bucket is a first-in, first-out list, and line L9 takes its first item.