Proofs: Bucket sort
These are the human proofs of Bucket sort, at full length.
Bucket sort sorts keys in [0, 1) and is stable full
This proof shows: correctness, stability.
Let hold keys with , and let . For each key, , so and line L3 appends to an existing list.
Lemma 1 (the buckets are ordered). If , then . Equivalently, if then .
Proof. If , then , and the floor function is non-decreasing, so . The first form is the contrapositive.
Lemma 2 (the scatter). After the loop of lines L2 and L3, each index appears in exactly one list, the list , and each list holds its keys in increasing order of input index.
Proof. By induction on the loop: before step , the keys are each in their own bucket list, in order of index. Step appends to the end of the list and changes no other list. So the claim holds before step , and for it is the lemma.
Theorem. BUCKET-SORT returns the keys of in non-decreasing order. If INSERTION-SORT is stable, keys that are equal appear in their input order.
Proof. After line L5, each list holds the same keys as before, in non-decreasing order, by the correctness of insertion sort. Let be the concatenation of line L6, and let be positions in with keys at and at .
- If both come from the same list , then , because is sorted.
- If they come from different lists and , then , because the concatenation puts the lists in order of their index. So , and Lemma 1 gives .
So is non-decreasing. By Lemma 2 it holds each key of exactly once.
For stability, let with . By Lemma 1 (with and ) both keys have the same bucket. By Lemma 2, is in front of in that list after line L3. A stable insertion sort keeps equal keys in their order, so is still in front after line L5, and also in .