11.8 Bucket sort¶
The sorting algorithms we have seen so far are comparison sorts: they order elements by comparing them with one another. Their worst-case time complexity has a lower bound of \(\Omega(n \log n)\). Next we will look at several non-comparison sorts that can run in linear time.
Bucket sort is a classic application of divide and conquer. It divides the data as evenly as possible among a series of ordered buckets, each covering a range of values. It then sorts each bucket separately and combines all the elements in bucket order.
11.8.1 How the algorithm works¶
Consider an array of length \(n\) whose elements are floating-point numbers in \([0, 1)\). Figure 11-13 shows how bucket sort works.
- Initialize \(k\) buckets and distribute the \(n\) elements among those \(k\) buckets.
- Sort each bucket separately (here we use the language's built-in sorting function).
- Combine the results in order, starting with the bucket for the smallest values.
Figure 11-13 Bucket sort procedure
Description of Figure 11-13: Distribute values among five buckets, sort each bucket, and concatenate them in order
Ten decimal values go into five buckets by range. Sort each bucket in ascending order, then concatenate the buckets in order to obtain a sorted array.
The input is nums = [0.49, 0.96, 0.82, 0.09, 0.57, 0.43, 0.91, 0.75, 0.15, 0.37]. All elements are floating-point numbers in [0, 1). The algorithm uses five buckets, each of width 0.2.
First place each number in the interval that contains it, including the left endpoint and excluding the right. Then sort the elements within each bucket. The five buckets in the middle of the figure show both operations complete. They do not show the original insertion order.
Finally, concatenate the buckets from the lowest range to the highest. Because their ranges do not overlap and each bucket is already sorted in ascending order, this produces the complete sorted array.
| Index | Value |
|---|---|
| 0 | 0.49 |
| 1 | 0.96 |
| 2 | 0.82 |
| 3 | 0.09 |
| 4 | 0.57 |
| 5 | 0.43 |
| 6 | 0.91 |
| 7 | 0.75 |
| 8 | 0.15 |
| 9 | 0.37 |
| Bucket range | Values in ascending order |
|---|---|
| [0,0.2) | 0.09, 0.15 |
| [0.2,0.4) | 0.37 |
| [0.4,0.6) | 0.43, 0.49, 0.57 |
| [0.6,0.8) | 0.75 |
| [0.8,1.0) | 0.82, 0.91, 0.96 |
The concatenated result is [0.09, 0.15, 0.37, 0.43, 0.49, 0.57, 0.75, 0.82, 0.91, 0.96].
Here is the code:
def bucket_sort(nums: list[float]):
"""Bucket sort"""
# Initialize k = n/2 buckets, expecting 2 elements per bucket
k = len(nums) // 2
buckets = [[] for _ in range(k)]
# 1. Distribute the array elements among the buckets
for num in nums:
# For inputs in [0, 1), use num * k to map each value to an index in [0, k-1]
i = int(num * k)
# Add num to bucket i
buckets[i].append(num)
# 2. Sort each bucket
for bucket in buckets:
# Use the built-in sort or another sorting algorithm
bucket.sort()
# 3. Traverse the buckets to combine the results
i = 0
for bucket in buckets:
for num in bucket:
nums[i] = num
i += 1
/* Bucket sort */
void bucketSort(vector<float> &nums) {
// Initialize k = n/2 buckets, expecting 2 elements per bucket
int k = nums.size() / 2;
vector<vector<float>> buckets(k);
// 1. Distribute the array elements among the buckets
for (float num : nums) {
// For inputs in [0, 1), use num * k to map each value to an index in [0, k-1]
int i = num * k;
// Add num to bucket bucket_idx
buckets[i].push_back(num);
}
// 2. Sort each bucket
for (vector<float> &bucket : buckets) {
// Use the built-in sort or another sorting algorithm
sort(bucket.begin(), bucket.end());
}
// 3. Traverse the buckets to combine the results
int i = 0;
for (vector<float> &bucket : buckets) {
for (float num : bucket) {
nums[i++] = num;
}
}
}
/* Bucket sort */
void bucketSort(float[] nums) {
// Initialize k = n/2 buckets, expecting 2 elements per bucket
int k = nums.length / 2;
List<List<Float>> buckets = new ArrayList<>();
for (int i = 0; i < k; i++) {
buckets.add(new ArrayList<>());
}
// 1. Distribute the array elements among the buckets
for (float num : nums) {
// For inputs in [0, 1), use num * k to map each value to an index in [0, k-1]
int i = (int) (num * k);
// Add num to bucket i
buckets.get(i).add(num);
}
// 2. Sort each bucket
for (List<Float> bucket : buckets) {
// Use the built-in sort or another sorting algorithm
Collections.sort(bucket);
}
// 3. Traverse the buckets to combine the results
int i = 0;
for (List<Float> bucket : buckets) {
for (float num : bucket) {
nums[i++] = num;
}
}
}
/* Bucket sort */
void BucketSort(float[] nums) {
// Initialize k = n/2 buckets, expecting 2 elements per bucket
int k = nums.Length / 2;
List<List<float>> buckets = [];
for (int i = 0; i < k; i++) {
buckets.Add([]);
}
// 1. Distribute the array elements among the buckets
foreach (float num in nums) {
// For inputs in [0, 1), use num * k to map each value to an index in [0, k-1]
int i = (int)(num * k);
// Add num to bucket i
buckets[i].Add(num);
}
// 2. Sort each bucket
foreach (List<float> bucket in buckets) {
// Use the built-in sort or another sorting algorithm
bucket.Sort();
}
// 3. Traverse the buckets to combine the results
int j = 0;
foreach (List<float> bucket in buckets) {
foreach (float num in bucket) {
nums[j++] = num;
}
}
}
/* Bucket sort */
func bucketSort(nums []float64) {
// Initialize k = n/2 buckets, expecting 2 elements per bucket
k := len(nums) / 2
buckets := make([][]float64, k)
for i := 0; i < k; i++ {
buckets[i] = make([]float64, 0)
}
// 1. Distribute the array elements among the buckets
for _, num := range nums {
// For inputs in [0, 1), use num * k to map each value to an index in [0, k-1]
i := int(num * float64(k))
// Add num to bucket i
buckets[i] = append(buckets[i], num)
}
// 2. Sort each bucket
for i := 0; i < k; i++ {
// Use the built-in slice sort or another sorting algorithm
sort.Float64s(buckets[i])
}
// 3. Traverse the buckets to combine the results
i := 0
for _, bucket := range buckets {
for _, num := range bucket {
nums[i] = num
i++
}
}
}
/* Bucket sort */
func bucketSort(nums: inout [Double]) {
// Initialize k = n/2 buckets, expecting 2 elements per bucket
let k = nums.count / 2
var buckets = (0 ..< k).map { _ in [Double]() }
// 1. Distribute the array elements among the buckets
for num in nums {
// For inputs in [0, 1), use num * k to map each value to an index in [0, k-1]
let i = Int(num * Double(k))
// Add num to bucket i
buckets[i].append(num)
}
// 2. Sort each bucket
for i in buckets.indices {
// Use the built-in sort or another sorting algorithm
buckets[i].sort()
}
// 3. Traverse the buckets to combine the results
var i = nums.startIndex
for bucket in buckets {
for num in bucket {
nums[i] = num
i += 1
}
}
}
/* Bucket sort */
function bucketSort(nums) {
// Initialize k = n/2 buckets, expecting 2 elements per bucket
const k = nums.length / 2;
const buckets = [];
for (let i = 0; i < k; i++) {
buckets.push([]);
}
// 1. Distribute the array elements among the buckets
for (const num of nums) {
// For inputs in [0, 1), use num * k to map each value to an index in [0, k-1]
const i = Math.floor(num * k);
// Add num to bucket i
buckets[i].push(num);
}
// 2. Sort each bucket
for (const bucket of buckets) {
// Use the built-in sort or another sorting algorithm
bucket.sort((a, b) => a - b);
}
// 3. Traverse the buckets to combine the results
let i = 0;
for (const bucket of buckets) {
for (const num of bucket) {
nums[i++] = num;
}
}
}
/* Bucket sort */
function bucketSort(nums: number[]): void {
// Initialize k = n/2 buckets, expecting 2 elements per bucket
const k = nums.length / 2;
const buckets: number[][] = [];
for (let i = 0; i < k; i++) {
buckets.push([]);
}
// 1. Distribute the array elements among the buckets
for (const num of nums) {
// For inputs in [0, 1), use num * k to map each value to an index in [0, k-1]
const i = Math.floor(num * k);
// Add num to bucket i
buckets[i].push(num);
}
// 2. Sort each bucket
for (const bucket of buckets) {
// Use the built-in sort or another sorting algorithm
bucket.sort((a, b) => a - b);
}
// 3. Traverse the buckets to combine the results
let i = 0;
for (const bucket of buckets) {
for (const num of bucket) {
nums[i++] = num;
}
}
}
/* Bucket sort */
void bucketSort(List<double> nums) {
// Initialize k = n/2 buckets, expecting 2 elements per bucket
int k = nums.length ~/ 2;
List<List<double>> buckets = List.generate(k, (index) => []);
// 1. Distribute the array elements among the buckets
for (double _num in nums) {
// For inputs in [0, 1), use _num * k to map each value to an index in [0, k-1]
int i = (_num * k).toInt();
// Add _num to bucket bucket_idx
buckets[i].add(_num);
}
// 2. Sort each bucket
for (List<double> bucket in buckets) {
bucket.sort();
}
// 3. Traverse the buckets to combine the results
int i = 0;
for (List<double> bucket in buckets) {
for (double _num in bucket) {
nums[i++] = _num;
}
}
}
/* Bucket sort */
fn bucket_sort(nums: &mut [f64]) {
// Initialize k = n/2 buckets, expecting 2 elements per bucket
let k = nums.len() / 2;
let mut buckets = vec![vec![]; k];
// 1. Distribute the array elements among the buckets
for &num in nums.iter() {
// For inputs in [0, 1), use num * k to map each value to an index in [0, k-1]
let i = (num * k as f64) as usize;
// Add num to bucket i
buckets[i].push(num);
}
// 2. Sort each bucket
for bucket in &mut buckets {
// Use the built-in sort or another sorting algorithm
bucket.sort_by(|a, b| a.partial_cmp(b).unwrap());
}
// 3. Traverse the buckets to combine the results
let mut i = 0;
for bucket in buckets.iter() {
for &num in bucket.iter() {
nums[i] = num;
i += 1;
}
}
}
/* Bucket sort */
void bucketSort(float nums[], int n) {
int k = n / 2; // Initialize k = n/2 buckets
int *sizes = malloc(k * sizeof(int)); // Track the size of each bucket
float **buckets = malloc(k * sizeof(float *)); // Array of dynamic arrays (buckets)
// Preallocate enough space for each bucket
for (int i = 0; i < k; ++i) {
buckets[i] = (float *)malloc(n * sizeof(float));
sizes[i] = 0;
}
// 1. Distribute the array elements among the buckets
for (int i = 0; i < n; ++i) {
int idx = (int)(nums[i] * k);
buckets[idx][sizes[idx]++] = nums[i];
}
// 2. Sort each bucket
for (int i = 0; i < k; ++i) {
qsort(buckets[i], sizes[i], sizeof(float), compare);
}
// 3. Combine the sorted buckets
int idx = 0;
for (int i = 0; i < k; ++i) {
for (int j = 0; j < sizes[i]; ++j) {
nums[idx++] = buckets[i][j];
}
// Free memory
free(buckets[i]);
}
}
/* Bucket sort */
fun bucketSort(nums: FloatArray) {
// Initialize k = n/2 buckets, expecting 2 elements per bucket
val k = nums.size / 2
val buckets = mutableListOf<MutableList<Float>>()
for (i in 0..<k) {
buckets.add(mutableListOf())
}
// 1. Distribute the array elements among the buckets
for (num in nums) {
// For inputs in [0, 1), use num * k to map each value to an index in [0, k-1]
val i = (num * k).toInt()
// Add num to bucket i
buckets[i].add(num)
}
// 2. Sort each bucket
for (bucket in buckets) {
// Use the built-in sort or another sorting algorithm
bucket.sort()
}
// 3. Traverse the buckets to combine the results
var i = 0
for (bucket in buckets) {
for (num in bucket) {
nums[i++] = num
}
}
}
### Bucket sort ###
def bucket_sort(nums)
# Initialize k = n/2 buckets, expecting 2 elements per bucket
k = nums.length / 2
buckets = Array.new(k) { [] }
# 1. Distribute the array elements among the buckets
nums.each do |num|
# For inputs in [0, 1), use num * k to map each value to an index in [0, k-1]
i = (num * k).to_i
# Add num to bucket i
buckets[i] << num
end
# 2. Sort each bucket
buckets.each do |bucket|
# Use the built-in sort or another sorting algorithm
bucket.sort!
end
# 3. Traverse the buckets to combine the results
i = 0
buckets.each do |bucket|
bucket.each do |num|
nums[i] = num
i += 1
end
end
end
Visualize execution
11.8.2 Algorithm properties¶
Bucket sort is well suited to very large datasets. Suppose the input contains one million elements and the system has too little memory to load them all at once. We can distribute the data among 1,000 buckets, sort each bucket separately, and then combine the results.
- Time complexity: \(O(n + k)\). If the elements are evenly distributed, each bucket holds \(\frac{n}{k}\) elements. If sorting one bucket takes \(O(\frac{n}{k} \log\frac{n}{k})\) time, sorting all the buckets takes \(O(n \log\frac{n}{k})\) time. As the number of buckets \(k\) grows large, this approaches \(O(n)\). Combining the results requires visiting all buckets and elements, which takes \(O(n + k)\) time. In the worst case, all the data lands in one bucket, and sorting it takes \(O(n^2)\) time.
- Space complexity: \(O(n + k)\), out-of-place. The algorithm needs extra space for \(k\) buckets and a total of \(n\) elements.
- Bucket sort is stable if the algorithm used to sort each bucket is stable.
11.8.3 Distributing the elements evenly¶
In theory, bucket sort can run in \(O(n)\) time. The challenge is to distribute the elements evenly among the buckets, since real data often has an uneven distribution. Suppose we want to divide all the products on Taobao evenly among 10 buckets by price. Many products cost less than 100 yuan, and very few cost more than 1,000 yuan. Dividing the price range into 10 equal intervals would give the buckets vastly different numbers of products.
To distribute the products more evenly, first choose rough boundaries and divide the data among 3 buckets. Then split each crowded bucket into 3 more buckets, repeating until all buckets hold roughly the same number of elements.
As Figure 11-14 shows, this method builds a recursion tree. The aim is to make the counts at the leaves as nearly equal as possible. You need not split the data into 3 buckets every time. Choose a split that suits the data.
Figure 11-14 Splitting buckets recursively
Description of Figure 11-14: Recursively split crowded price buckets
First divide the products into three price buckets. Then recursively split the crowded buckets holding 65% and 35% of the data to obtain seven more evenly populated leaf buckets.
Each percentage is a share of all products, not just of its parent bucket. The figure gives price range labels and bucket shares but does not specify the total number of products, currency, or a complete rule for assigning endpoints.
Branching arrows below “Product data” show successive subdivisions. Buckets that are not split further remain leaves. The first split gives three price buckets: <100 holds 65%, 100–500 holds 20%, and >500 holds 15%. Since <100 holds 65% of all products, it is split into three more buckets.
The second level divides <100 into <10 with 18%, 10–50 with 35%, and 50–100 with 12%. Their shares add up to 18% + 35% + 12% = 65%. The 10–50 bucket still holds a particularly large share (35%), so it is divided into 10–20 with 13%, 20–35 with 12%, and 35–50 with 10%. Their shares add up to 13% + 12% + 10% = 35%.
“Resulting groups” on the right lists the seven leaf buckets of the recursion tree (see the table). Their shares range from 10% to 20%, much more evenly distributed than the initial 65%, 20%, and 15%. The intermediate 65% and 35% totals belong to parent buckets that were split, so they do not count again in the result.
| Price interval shown | Share of all data |
|---|---|
| <10 | 18% |
| 10–20 | 13% |
| 20–35 | 12% |
| 35–50 | 10% |
| 50–100 | 12% |
| 100–500 | 20% |
| >500 | 15% |
The seven leaf shares add up to 100%. Each leaf holds 10% to 20%, so the data is more evenly distributed after splitting. An implementation must complete the range labels with explicit endpoint rules.
If we know the probability distribution of product prices in advance, we can use it to choose the price boundaries for each bucket. We do not necessarily need to measure the distribution explicitly. A probability model that reflects the characteristics of the data can approximate it.
In Figure 11-15, we assume that product prices follow a normal distribution. This lets us choose price intervals that distribute the products evenly among the buckets.
Figure 11-15 Defining buckets from a probability distribution
Description of Figure 11-15: Choosing bucket ranges from a price distribution
Choose boundaries using the distribution of product prices so that data points have roughly equal chances of falling into each bucket. This keeps the data from crowding into just a few buckets.
The horizontal axis shows product prices, labeled 0, 3, 10, 25, 80, 200, and +∞ from left to right. The vertical axis shows probability density, with ticks from 0.0 to 0.4. The gray bell-shaped curve peaks near a price of 25. It illustrates the shape of the distribution. The figure gives neither the distribution parameters nor exact bucket probabilities.
The horizontal axis is schematic and nonlinear. For example, the price difference from 0 to 3 is 3, and the difference from 80 to 200 is 120, but the horizontal distances in pixels are not proportional to those differences. The apparent bucket widths therefore do not give the actual price spans, and measuring the area under the displayed curve cannot yield exact bucket probabilities.
The six braces below the curve correspond to the six buckets in the table. The rightmost bucket has no finite upper bound. The aim is to use interval probabilities from the actual distribution to give each bucket roughly the same expected number of data points. The figure does not give exact probabilities or establish that the six probabilities are identical.
| Bucket number | Price range shown |
|---|---|
| 1 | <3 |
| 2 | 3–10 |
| 3 | 10–25 |
| 4 | 25–80 |
| 5 | 80–200 |
| 6 | >200 |
The label <3 excludes 3, and >200 excludes 200. Middle labels such as 3–10 leave endpoint inclusion unspecified. If the six buckets cover the entire price range, 3 must belong to the second bucket and 200 to the fifth. This follows from the coverage requirement. The figure does not give a complete endpoint rule, so an implementation must specify where shared boundaries such as 10, 25, and 80 belong.