Proofs: Hoare partition scheme
These are the human proofs of Hoare partition scheme, at full length.
Hoare partition stays in range, stops, and splits the range correctly full
This proof shows: correctness, termination.
Let and let at the call. A round is one pass through lines L4 to L7. Each change of is an exchange of two items of , so the multiset of the range never changes, and no item outside the range changes. These are the three properties of CLRS, Problem 7-1.
Claim. (a) Lines L4 and L5 read only indices in . (b) The call stops and returns with . (c) At the return, each item of is at most , and each item of is at least . So each item of is at most each item of .
The first round. The scan of line L4 starts at and moves left. , so it stops at some . The scan of line L5 starts at , and (the exchange of this round has not happened yet), so it stops at once with . Both scans read only indices in . If , then , and line L7 returns , which is less than . The items were passed by the scan of , so they are greater than , and . So (c) holds. Otherwise , and line L6 exchanges and . After it, is the old , and is .
Invariant. At the start of each round after the first, with the current and :
(P) . Each item of is at most , and each item of is at least .
Initialization. After the first round with an exchange, and . . The items are greater than , and . So (P) holds.
A round. Assume (P). The scan of line L4 starts at and moves left. The item is at most , so the scan stops at some . It passed the items , which are greater than . So each item of is at least , and . The scan of line L5 starts at and moves right. The item is at least , so the scan stops at some . It passed the items , which are less than . So each item of is at most . Both scans read only indices in , which proves (a) for this round.
If , line L6 exchanges and . Before the exchange and , so after it and . So is at most and is at least , with , and (P) holds for the next round.
If , line L7 returns . Then or . In both cases each item of is at most : the items up to by the scan of , and itself because the scan of stopped there. Each item of is at least , as shown above. So (c) holds. Also , and , so , which is (b) in this case.
Termination. In each round with an exchange, grows by at least 1 and drops by at least 1, so drops by at least 2. While (P) holds, . So after at most rounds, the test of line L6 fails, and the call returns.
Consequence for quicksort. Since , both ranges and are not empty and are strictly shorter than . By (c) and induction on the length, quicksort that sorts both ranges sorts .