Lesson 44 · Core algorithms

Bucket Sort: Distribution, Spread and Cost

Scatter values into ranges, sort each small bucket, then read the buckets back in order.

Bucket Sort: Distribution, Spread and Cost concept diagramA visual explanation of the layout and operations shown in this lesson.scatter by range, sort each bucket, then concatenate0.780.170.390.260.720.940.0-0.20.170.2-0.40.260.390.4-0.6empty0.6-0.80.720.780.8-1.00.94uniform input averages O(n); if one bucket takes everything it is only as fast as that bucket's sort
1

How Bucket Sort Works

  1. Create n empty buckets, one per input value
  2. For each value, compute its bucket index and append it there
  3. Sort each bucket, usually with insertion sort
  4. Concatenate the buckets from bucket 0 upward

Bucket sort splits the range of the input into equal sub-ranges called buckets, drops each value into its bucket, sorts every bucket on its own, and reads the buckets back from lowest to highest. Because each bucket covers a range that sits entirely below the next one, the result is sorted without any merge step.

The bucket for a value is computed, not found by comparison. For values in [0, 1) and n buckets it is floor(n × value); for any other range it is floor(n × (value − min) / (max − min)), capped at n − 1. That arithmetic is what lets the first pass run in linear time.

  • Scatter is one pass of arithmetic
  • Buckets are already in order relative to each other
  • All the comparisons happen inside the buckets
2

Worked Example: Six Values in [0, 1)

Sort 0.78, 0.17, 0.39, 0.26, 0.72, 0.94 with six buckets, bucket = floor(6 × value). 0.78 goes to bucket 4 (6 × 0.78 = 4.68), 0.17 to bucket 1, 0.39 to bucket 2, 0.26 to bucket 1, 0.72 to bucket 4 and 0.94 to bucket 5. Buckets 0 and 3 stay empty.

Bucket 1 holds 0.17, 0.26, already in order. Bucket 4 holds 0.78, 0.72 and needs one shift to become 0.72, 0.78. Reading buckets 0 to 5 gives 0.17, 0.26, 0.39, 0.72, 0.78, 0.94.

The whole sort took six index calculations and two comparisons. Insertion sort on the full array could need fifteen. The tracer below follows this run and then the inputs that break it.

  • Bucket index = floor(6 × value)
  • Two buckets hold two values; the rest hold one or none
  • Two comparisons in total inside the buckets
3

Time and Space Complexity

How long bucket sort takes depends on how the values spread. With evenly spread values the expected total cost is O(n + n²/k + k): n to scatter, k to walk the buckets, and n²/k for insertion sort on buckets that each hold about n/k values. With k = n this is O(n) on average.

Extra space is O(n + k) for the buckets and their contents. Bucket sort does not sort in place.

The average depends on the input, not on the algorithm. A sort like merge sort costs O(n log n) on any input; bucket sort is linear only when the data cooperates.

Cost by how the input is spread, n values, k buckets
InputTimeWhy
Evenly spread over the rangeO(n + k), O(n) when k ≈ nAbout one value per bucket
Mildly clusteredBetween O(n) and O(n²)A few buckets hold several values
Almost all in one bucketO(n²) with insertion sortOne bucket holds everything
  • Average O(n) needs evenly spread values and k ≈ n buckets
  • Space O(n + k)
  • Cost depends on the data, not just on n
Key reference

Terms, operations, and practical uses

Terms

  • BucketOne equal-width slice of the value range, holding the values that fall in it.
  • ScatterThe pass that computes each value's bucket index and appends the value there.
  • GatherReading the sorted buckets from lowest to highest into the output.

Choosing the bucket count

  • k = nOne bucket per value gives O(n) expected time on evenly spread input.
  • Fewer bucketsLess memory, but each bucket holds more values and the inner sort costs more.
  • Range from min and maxOne extra pass; needed when values are not already in [0, 1).
Implementation

Code in Python, C++ and Java

def insertion_sort(values):
    for i in range(1, len(values)):
        current = values[i]
        j = i - 1
        while j >= 0 and values[j] > current:
            values[j + 1] = values[j]
            j -= 1
        values[j + 1] = current
    return values


def bucket_sort(values):
    if not values:
        return values
    count = len(values)
    buckets = [[] for _ in range(count)]
    # The bucket index is arithmetic, so scattering is one linear pass.
    for value in values:
        index = min(int(value * count), count - 1)
        buckets[index].append(value)
    output = []
    for bucket in buckets:
        output.extend(insertion_sort(bucket))
    return output


print(bucket_sort([0.78, 0.17, 0.39, 0.26, 0.72, 0.94]))
#include <iostream>
#include <vector>
using namespace std;

// Insertion sort is the conventional per-bucket choice: stable, and fast on
// the two or three items a bucket usually holds.
void insertionSort(vector<double>& values) {
    for (size_t i = 1; i < values.size(); i++) {
        double current = values[i];
        int j = (int)i - 1;
        while (j >= 0 && values[j] > current) {
            values[j + 1] = values[j];
            j--;
        }
        values[j + 1] = current;
    }
}

vector<double> bucketSort(const vector<double>& values) {
    if (values.empty()) return values;
    int count = (int)values.size();
    vector<vector<double>> buckets(count);
    // The bucket index is arithmetic, so scattering is one linear pass.
    for (double value : values) {
        int index = min((int)(value * count), count - 1);
        buckets[index].push_back(value);
    }
    vector<double> output;
    for (auto& bucket : buckets) {
        insertionSort(bucket);
        for (double v : bucket) output.push_back(v);
    }
    return output;
}

int main() {
    vector<double> sorted = bucketSort({0.78, 0.17, 0.39, 0.26, 0.72, 0.94});
    cout << "[";
    for (size_t i = 0; i < sorted.size(); i++) cout << (i ? ", " : "") << sorted[i];
    cout << "]" << endl;
    return 0;
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    // Insertion sort is the conventional per-bucket choice: stable, and fast
    // on the two or three items a bucket usually holds.
    static void insertionSort(List<Double> values) {
        for (int i = 1; i < values.size(); i++) {
            double current = values.get(i);
            int j = i - 1;
            while (j >= 0 && values.get(j) > current) {
                values.set(j + 1, values.get(j));
                j--;
            }
            values.set(j + 1, current);
        }
    }

    static double[] bucketSort(double[] values) {
        if (values.length == 0) return values;
        int count = values.length;
        List<List<Double>> buckets = new ArrayList<>();
        for (int i = 0; i < count; i++) buckets.add(new ArrayList<>());
        // The bucket index is arithmetic, so scattering is one linear pass.
        for (double value : values) {
            int index = Math.min((int) (value * count), count - 1);
            buckets.get(index).add(value);
        }
        double[] output = new double[count];
        int at = 0;
        for (List<Double> bucket : buckets) {
            insertionSort(bucket);
            for (double v : bucket) output[at++] = v;
        }
        return output;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(
            bucketSort(new double[]{0.78, 0.17, 0.39, 0.26, 0.72, 0.94})));
    }
}
Watch it run

Step through it

Running on [0.78, 0.17, 0.39, 0.26, 0.72, 0.94]

the line from 0 to 1, cut into 6 bucketsinput 0.78 0.17 0.39 0.26 0.72 0.94 · bucket = floor(6 × value)0.001.000.780.170.390.260.720.94bucket 0bucket 1bucket 2bucket 3bucket 4bucket 5
Step 1

Six values, six equal ranges

Six inputs, so six buckets, each covering one sixth of [0, 1). A value's bucket is floor(6 × value): plain arithmetic, no comparison with any other value. That is why the first pass costs one step per value however the values are ordered.

Output
1 / 13
4

Worst Case: One Full Bucket

In the bucket sort worst case, every value lands in one bucket. Then the scatter pass achieves nothing and the sort inside that bucket does all the work: O(n²) with insertion sort. Six values between 0.50 and 0.55 all give floor(6 × v) = 3; in descending order they cost 15 comparisons, n(n − 1)/2.

Taking the bucket ranges from the data's min and max fixes that example, but one outlier breaks the fix: with 0.50 to 0.54 and 9.0, the range is 8.5 wide and the five small values share bucket 0. Using a sort with an O(n log n) worst case inside each bucket caps the damage at O(n log n).

Two index bugs are worth checking. A value of exactly 1.0 gives index n, one past the last bucket, so the index must be capped at n − 1. A negative value gives a negative index: Java throws, C++ has undefined behaviour, and Python quietly uses bucket −1, the last one, which produces wrong output with no error.

  • One full bucket means O(n²) with insertion sort
  • Min-max ranges fix clustering, not outliers
  • Cap the index at n − 1; reject or shift negative values
5

Floating Point Numbers and When to Use It

Using bucket sort for floating point numbers needs no conversion: the bucket index only needs arithmetic on the value. That is where it differs from counting sort and radix sort, which need integer keys or keys made of digits; those two are linear on any valid input, while bucket sort is linear only on well spread input.

It fits data whose distribution is known: random numbers in 0, 1), normalised scores, sensor readings in a fixed range, hash values. For unknown or skewed data, a comparison sort from the [sorting algorithms overview is the safer choice.

Stability comes from two places: values are appended to buckets in input order, and the sort inside each bucket must itself be stable. Insertion sort is stable, which is one more reason it is the usual pick.

  • Use it on floats with a known, even spread
  • Use a comparison sort when the spread is unknown
  • Stable when appends keep input order and the inner sort is stable