Proofs: Three-way quicksort
These are the human proofs of Three-way quicksort, at full length.
Three-way quicksort sorts the array and keeps its items full
This proof shows: correctness.
We write for the multiset of the items of at the start of a call. All changes to the array are swaps of two items of the range, so the range always holds , and items outside the range do not change.
Lemma (the partition). Assume , and let be the item read at line L2. When the loop of lines L4 to L9 stops, , each item of is less than , each item of is equal to , and each item of is larger than .
Proof. We use this invariant, before each test of line L4:
(I) . Each item of is less than , each item of is equal to , and each item of is larger than .
Start. Line L3 sets and , so the three parts are empty.
Step. Assume (I) and , and let .
- If (line L5), line L6 swaps and . If , the old was equal to , and it moves to index ; if , nothing moves. Now and are equal to . After and grow by one, (I) holds.
- If (line L7), line L8 makes one smaller and swaps with . Now , so the large part grows by one item. The new came from the unseen part, and does not change. Since held before the step, holds after it, and (I) holds.
- Otherwise neither nor , so is equal to in the total order. Line L9 makes one larger, and the equal part grows by . (I) holds.
End. Each step makes smaller by exactly one, so the loop stops after steps with . Then (I) says that the range is the small part , the equal part and the large part . The item is in the range, and it is neither less than nor larger than , so it is in the equal part, and .
Theorem. After THREE-WAY-QUICKSORT, the range is sorted and holds , and no item outside the range changes.
Proof. By strong induction on . If , line L1 returns, and the range is sorted. Let , and assume the claim for all shorter ranges. By the lemma, the loop ends with the three parts and . The ranges and have fewer than items each, because the equal part is not empty. By the hypothesis, line L10 sorts the small part and changes nothing else; it permutes the small part, so its items stay less than . Line L11 does the same for the large part. So the range is a sorted part of items less than , then items equal to , then a sorted part of items larger than , and it is sorted. It holds , because all moves were swaps inside the range.
Termination. Each call on items makes two calls on fewer items, and each loop runs steps, so the algorithm stops.