Proofs: Lomuto partition scheme
These are the human proofs of Lomuto partition scheme, at full length.
The Lomuto partition puts the pivot at its place and keeps the items full
This proof shows: correctness.
Claim. Let , let be the multiset of the items of at the start, and let be the old . Then LOMUTO-PARTITION stops after steps of its loop and returns an index with . After the call, holds , , each item of is at most , and each item of is larger than . No item outside the range changes.
Proof. Lines L1 and L2 set and . We prove this invariant of the loop of line L3, before the step for , for :
(L) . Each item of is at most . Each item of is larger than . . The range holds , and nothing outside it has changed.
- Start. For , we have , so both parts are empty. No line has changed the array.
- A large item. Assume (L) for and . The test of line L4 fails, and nothing changes. Now holds only items larger than , so (L) holds for .
- A small item. Assume (L) for and . If , line L5 swaps with itself, and after line L6 the left part holds only items at most , while the large part is empty. If , then is in the large part, so . Line L5 swaps and , so now and . After line L6, the left part is with the old , all at most , and the large part is , all larger than . In both cases (L) holds for . The swap uses indices , so it does not touch or any index outside the range.
- End. The loop of line L3 runs for , so it stops after exactly steps, with (L) for . So , and , with .
- The last swap. Line L7 swaps and . If , nothing changes. If , the old is larger than and goes to index , which is in . In both cases, after the swap , and .
Line L8 returns . Each change was a swap of two indices in the range, so the range still holds and nothing outside it changed.
Rank of the pivot. The claim gives exactly items at most other than itself. So when the items are distinct, has rank in the range, and is the item that a sort of the range puts at index .