Algorithm Search⌘K

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 A[0…n−1]A[0 \ldots n-1] hold keys with 0≤A[i]<10 \le A[i] < 1, and let β(x)=⌊nx⌋\beta(x) = \lfloor n x \rfloor. For each key, 0≤nx<n0 \le n x < n, so β(x)∈{0,…,n−1}\beta(x) \in \{0, \ldots, n-1\} and line L3 appends to an existing list.

Lemma 1 (the buckets are ordered). If β(x)<β(y)\beta(x) < \beta(y), then x<yx < y. Equivalently, if x≤yx \le y then β(x)≤β(y)\beta(x) \le \beta(y).

Proof. If x≤yx \le y, then nx≤nyn x \le n y, and the floor function is non-decreasing, so β(x)≤β(y)\beta(x) \le \beta(y). The first form is the contrapositive. □\square

Lemma 2 (the scatter). After the loop of lines L2 and L3, each index ii appears in exactly one list, the list B[β(A[i])]B[\beta(A[i])], and each list holds its keys in increasing order of input index.

Proof. By induction on the loop: before step ii, the keys A[0],…,A[i−1]A[0], \ldots, A[i-1] are each in their own bucket list, in order of index. Step ii appends A[i]A[i] to the end of the list B[β(A[i])]B[\beta(A[i])] and changes no other list. So the claim holds before step i+1i + 1, and for i=ni = n it is the lemma. □\square

Theorem. BUCKET-SORT returns the keys of AA in non-decreasing order. If INSERTION-SORT is stable, keys that are equal appear in their input order.

Proof. After line L5, each list B[j]B[j] holds the same keys as before, in non-decreasing order, by the correctness of insertion sort. Let CC be the concatenation of line L6, and let p<qp < q be positions in CC with keys xx at pp and yy at qq.

  1. If both come from the same list B[j]B[j], then x≤yx \le y, because B[j]B[j] is sorted.
  2. If they come from different lists B[j]B[j] and B[j′]B[j'], then j<j′j < j', because the concatenation puts the lists in order of their index. So β(x)<β(y)\beta(x) < \beta(y), and Lemma 1 gives x<yx < y.

So CC is non-decreasing. By Lemma 2 it holds each key of AA exactly once.

For stability, let A[i]=A[i′]A[i] = A[i'] with i<i′i < i'. By Lemma 1 (with x≤yx \le y and y≤xy \le x) both keys have the same bucket. By Lemma 2, A[i]A[i] is in front of A[i′]A[i'] in that list after line L3. A stable insertion sort keeps equal keys in their order, so A[i]A[i] is still in front after line L5, and also in CC. ■\blacksquare

Back to Bucket sort