Algorithm Search⌘K

Proofs: External queue

These are the human proofs of External queue, at full length.

The external queue returns items in FIFO order and makes at most 2n/B block transfers full

This proof shows: correctness, complexity.

We use the pseudocode of the page with block size B≥1B \ge 1. The state is the head HH, the disk blocks D1,…,DkD_1, \ldots, D_k and the tail TT. Let σ=H⋅D1⋯Dk⋅T\sigma = H \cdot D_1 \cdots D_k \cdot T.

Invariant. At the start and after each operation: (I1) σ\sigma is the abstract queue, from the front to the back; (I2) each DjD_j has exactly BB items; (I3) ∣H∣≤B|H| \le B and ∣T∣<B|T| < B.

Base. For the empty queue all three parts are empty, so the invariant holds.

Enqueue. Line L1 appends xx to TT and so to σ\sigma, which is now the old queue followed by xx. Now ∣T∣≤B|T| \le B. If ∣T∣=B|T| = B, lines L3 and L4 append TT as a block Dk+1D_{k+1} and empty TT. This does not change σ\sigma, the new block has BB items, and ∣T∣=0|T| = 0. Otherwise ∣T∣<B|T| < B already. HH does not change.

Dequeue. If HH is not empty, only line L10 runs: it removes the first item of HH, which is the first item of σ\sigma. If HH is empty and k≥1k \ge 1, line L7 makes H=D1H = D_1 and removes D1D_1 from the disk part, so σ\sigma does not change and ∣H∣=B|H| = B. If HH is empty and k=0k = 0, then σ=T\sigma = T. If TT is empty the queue is empty, and line L8 reports the error. Otherwise line L9 moves TT into HH, which does not change σ\sigma, and gives ∣H∣<B|H| < B and ∣T∣=0|T| = 0. In both cases HH is now not empty, and line L10 removes and returns the first item of σ\sigma, the front of the queue. (I2) holds because no block was written, and (I3) holds because HH has at most BB items and only shrinks in line L10.

By induction the invariant holds after every operation, and each dequeue returns the oldest item that is still in the queue. □\square

Theorem (I/O bound). Starting from the empty queue, a sequence with ee enqueues and any number of dequeues, nn operations in all, makes at most ⌊e/B⌋\lfloor e/B \rfloor writes and at most as many reads, so at most 2⌊n/B⌋2\lfloor n/B \rfloor block transfers.

Proof. Writes. Follow one item xx. It enters TT in its enqueue (line L1). It leaves TT only through line L3, into a disk block, or through line L9, into HH. From a disk block it goes only to HH (line L7), and from HH only out of the queue (line L10). So xx is in at most one written block. Each write contains exactly BB items, all different, so the number of writes ww satisfies wB≤ewB \le e, and w≤⌊e/B⌋w \le \lfloor e/B \rfloor.

Reads. Each read in line L7 removes one block from the disk part, and blocks enter the disk part only by writes. So the number of reads is at most ww.

Hence the transfers number at most 2w≤2⌊e/B⌋≤2⌊n/B⌋2w \le 2\lfloor e/B \rfloor \le 2\lfloor n/B \rfloor. ■\blacksquare

Back to External queue