Proofs: Staircase search
These are the human proofs of Staircase search, at full length.
Staircase search finds x when it occurs, returns NIL otherwise, and reads at most m + n - 1 cells full
This proof shows: correctness, termination, complexity.
Let be an matrix, , with and for all indices in range, and let be a key. Write for the set of cells that hold . We prove three things about STAIRCASE-SEARCH: it stops after at most passes of the loop, a returned pair is in , and NIL is returned only when is empty.
Invariant. Before each test of line L2, every has and . Also and .
Start. Line L1 sets and . Every cell has and , so the first statement holds. The bounds hold since .
Step. A pass runs only when and , so is a cell. If , line L3 returns. Otherwise there are two cases.
- Case . Line L4 sets . Take . By the invariant and . Assume . Since column is sorted and , , which contradicts . So . The new bounds hold, since gives .
- Case . Line L5 sets . Take , with and . Assume . Since row is sorted and , , a contradiction. So . The new bounds hold, since gives .
So the invariant holds before the next test.
A returned pair is correct. Line L3 returns only when , so .
NIL is correct. Line L6 runs only when the test of line L2 fails, that is or . If , the invariant gives or . Both contradict that is a cell, so is empty.
Termination and the bound. Let . At the start . Each pass that does not return raises by one or lowers by one, so it raises by exactly one. A pass runs only when and , so at the start of each pass. The values of at the starts of the passes are distinct integers in , and there are such integers. So the loop makes at most passes, and each pass reads one cell. When or the test of line L2 fails at once and no cell is read.
Which copy is returned. Assume is not empty and the walk returns . By the invariant, every cell of has row , so is the smallest row that holds , and every cell of in row has column , so is the largest column of in row .