Post

Bucket Sort in Java

Learn how Bucket Sort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.

Bucket Sort in Java

Introduction

Bucket Sort is a distribution sort. It divides the range of the values into equal-width buckets, drops every value into the bucket for its part of the range, sorts each bucket on its own, and then joins the buckets back together in order.

Three ideas carry the whole algorithm:

  • Buckets: a list of small containers, each covering one slice of the range from the smallest to the largest value.
  • Hash: a function that maps a value to its bucket by where it lies in the range, so that every value in one bucket is smaller than or equal to every value in the next.
  • Concatenation: after each bucket has been sorted, reading the buckets from first to last gives the whole array in order.

Bucket Sort is at its best on values that are spread evenly over a known range, such as random floating-point numbers between 0 and 1. Then every bucket receives only a few values, sorting them is cheap, and the whole sort runs in linear time on average. It is the idea behind many external sorts and parallel sorts, where each bucket can be sorted on its own.

This article uses Bucket Sort with ArrayList buckets and Collections.sort: the values are distributed into a list of lists, each bucket is sorted with Java’s built-in sort, and the buckets are copied back into the array.

Performance Characteristics

Bucket Sort is only as fast as its buckets are even: the work depends on how well the hash spreads the values, and so on how they are distributed.

Time Complexity

Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.

In the table, $n$ is the number of values and $k$ is the number of buckets.

CaseTimeWhen it happens
Best$O(n + k)$The values are spread evenly, so each bucket holds about $n / k$ values
Average$O(n + k)$Uniformly distributed input, with $k$ proportional to $n$
Worst$O(n \log n)$All values land in one bucket, which is then sorted by Collections.sort

Why $n + k$? Finding the minimum and maximum, distributing the values and copying them back each walk the array once ($n$ work), and creating and visiting the buckets costs $k$. If each bucket holds only a few values, sorting all of them adds about $O(n)$ more. When one bucket gets most of the values, the cost becomes that of sorting it: $O(n \log n)$ here, because Collections.sort is a TimSort. A textbook version that sorts buckets with insertion sort would be $O(n^2)$ in that case.

Bucket Sort needs data that spreads evenly over its range. A few extreme values stretch the range and push everything else into one or two buckets. When the data is skewed, choosing the bucket boundaries from a sample of the values (as in sample sort) keeps the buckets even.

Space Complexity

Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.

PropertyValue
Space$O(n + k)$: every value is stored once in a bucket, plus the $k$ bucket lists
In placeNo (the values are copied into buckets and back)
StableYes (values are added to buckets in order, and Collections.sort is stable)

Algorithm (Pseudo Code)

Bucket Sort starts by finding the smallest and largest value, which together set the range, and creating a number of empty buckets. Each value is then mapped to a bucket by where it lies in the range: a value close to the minimum goes into the first bucket, a value close to the maximum into the last. Because the buckets cover consecutive slices of the range, every value in one bucket is smaller than or equal to every value in the buckets after it.

Next, the buckets are visited from first to last. Each bucket is sorted on its own, and its values are copied back into the array, one after the other. Since the buckets are already in order relative to each other, sorting the inside of each bucket is all that’s needed, and when the last bucket has been copied, the whole array is sorted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
sort(array):
    min = findMin(array), max = findMax(array)
    numberOfBuckets = max(n / 10, 1)
    buckets = numberOfBuckets empty lists
    for each element in array:
        buckets[hash(element, min, max, numberOfBuckets)].add(element)
    index = 0
    for each bucket in buckets:
        sort(bucket)
        for each element in bucket: array[index++] = element

hash(element, min, max, numberOfBuckets):
    normalized = (element - min) / (max - min)        // 0.0 to 1.0
    return (int) (normalized * (numberOfBuckets - 1))

After the distribution, every value in bucket i is smaller than or equal to every value in bucket i + 1, so sorting each bucket and joining them sorts the array.

The Java code below doesn’t compute element - min. It uses element.compareTo(min), which for numbers only says which value is larger, not by how much. The warning in the hash section shows what that does to the buckets.

Visualization

The visualization below follows the Java code line by line, starting with the values 0 to 9 in shuffled order.

Two settings differ from the code, so that the buckets do something visible. The code creates one bucket per ten values, which gives a single bucket for ten values, so the visualization uses 5 buckets. And it starts with the hash the Javadoc describes, by distance from the minimum; tick Hash with compareTo to see what the Java code actually does.

Each step shows the array, the buckets and the line of code that is running, with a short explanation of what just happened:

  • Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
  • Play: press Play to run the steps automatically, and press it again to pause.
  • Shuffle: press the shuffle button to start again with a new random order.
  • Buckets: choose the number of buckets in the footer: 1 (what the code uses for ten values), 2, 3 or 5.
  • Hash with compareTo: tick it to hash with compareTo, exactly as the Java code does.
  • Pointer: I is index, the next position in the array to be written.
  • Colours: the value being read, or the bucket being sorted, is amber, a value being added to a bucket or copied back is salmon, and values copied back into the array are green.
read / sorting added / copied back in the array I = index

Java Code

The implementation is a BucketSort class with one public method, sort, and seven private methods: findMin and findMax find the range, calculateNumberOfBuckets and initializeBuckets set up the buckets, distributeElementsIntoBuckets and hash fill them, and concatenateBuckets sorts each bucket and copies it back. The constant BUCKET_DIVISOR = 10 sets the number of buckets. Two small helpers, less and greater, live in a separate SortUtils class.

The complete code is in the algorithm-examples repository on GitHub: BucketSort.java, with the helpers in SortUtils.java.

sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
    if (array.length == 0) {
        return array;
    }

    T min = findMin(array);
    T max = findMax(array);
    int numberOfBuckets = calculateNumberOfBuckets(array.length);

    List<List<T>> buckets = initializeBuckets(numberOfBuckets);
    distributeElementsIntoBuckets(array, buckets, min, max, numberOfBuckets);

    return concatenateBuckets(buckets, array);
}

sort is the entry point. It accepts an array of any Comparable type, and an empty array comes straight back. Otherwise it finds the smallest and largest value, sets up the buckets, distributes the values, and lets concatenateBuckets sort the buckets and write them back. The array is sorted in place and returned.

findMin and findMax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private <T extends Comparable<T>> T findMin(T[] array) {
    T min = array[0];
    for (T element : array) {
        if (SortUtils.less(element, min)) {
            min = element;
        }
    }
    return min;
}

private <T extends Comparable<T>> T findMax(T[] array) {
    T max = array[0];
    for (T element : array) {
        if (SortUtils.greater(element, max)) {
            max = element;
        }
    }
    return max;
}

findMin and findMax each walk the array once and keep the smallest or largest value seen so far. Together they set the range that the buckets cover.

calculateNumberOfBuckets and initializeBuckets

1
2
3
4
5
6
7
8
9
10
11
private int calculateNumberOfBuckets(final int arrayLength) {
    return Math.max(arrayLength / BUCKET_DIVISOR, 1);
}

private <T extends Comparable<T>> List<List<T>> initializeBuckets(int numberOfBuckets) {
    List<List<T>> buckets = new ArrayList<>(numberOfBuckets);
    for (int i = 0; i < numberOfBuckets; i++) {
        buckets.add(new ArrayList<>());
    }
    return buckets;
}

calculateNumberOfBuckets uses one bucket for every ten values, with a minimum of one, so with a uniform spread each bucket holds about ten values. initializeBuckets creates that many empty ArrayLists. Arrays with fewer than 20 values get a single bucket, which turns the whole sort into one call to Collections.sort.

distributeElementsIntoBuckets and hash

1
2
3
4
5
6
7
8
9
10
11
12
private <T extends Comparable<T>> void distributeElementsIntoBuckets(T[] array, List<List<T>> buckets, final T min, final T max, final int numberOfBuckets) {
    for (final T element : array) {
        int bucketIndex = hash(element, min, max, numberOfBuckets);
        buckets.get(bucketIndex).add(element);
    }
}

private <T extends Comparable<T>> int hash(final T element, final T min, final T max, final int numberOfBuckets) {
    double range = max.compareTo(min);
    double normalizedValue = element.compareTo(min) / range;
    return (int) (normalizedValue * (numberOfBuckets - 1));
}

distributeElementsIntoBuckets walks the array in order and adds each value to the bucket that hash chooses. Values are added at the end of their bucket, so values that land in the same bucket keep their original order.

hash is meant to normalise the value to a number between 0.0 and 1.0, by where it lies between min and max, and to scale that to a bucket index. Because the result is multiplied by numberOfBuckets - 1 and then rounded down, only the maximum itself reaches the last bucket.

hash uses compareTo as if it returned the distance between two values, but the Comparable contract only promises its sign. Integer.compareTo and Double.compareTo return -1, 0 or 1, so range is 1 and normalizedValue is 0 for the minimum and 1 for everything else. Every value except the minimum goes into the last bucket: 40 integers from 0 to 975 fill four buckets as [1, 0, 0, 39]. The array is still sorted correctly, because Collections.sort sorts that one big bucket, but the buckets do no work. For String, compareTo returns character or length differences, and the index can go past the last bucket: 20 strings including "aa", "az" and "b" throw an IndexOutOfBoundsException. A working bucket sort needs a numeric key, for example a ToDoubleFunction<T>, and should compute (key(element) - key(min)) / (key(max) - key(min)).

concatenateBuckets

1
2
3
4
5
6
7
8
9
10
private <T extends Comparable<T>> T[] concatenateBuckets(Iterable<List<T>> buckets, T[] array) {
    int index = 0;
    for (List<T> bucket : buckets) {
        Collections.sort(bucket);
        for (T element : bucket) {
            array[index++] = element;
        }
    }
    return array;
}

concatenateBuckets visits the buckets from first to last. It sorts each bucket with Collections.sort, a stable TimSort, and copies its values into the array at index, which moves forward by one for every value written. Because every bucket covers a higher part of the range than the one before it, the array is sorted when the last bucket has been copied.

less and greater

1
2
3
4
5
6
7
public static <T extends Comparable<T>> boolean less(T firstElement, T secondElement) {
    return firstElement.compareTo(secondElement) < 0;
}

public static <T extends Comparable<T>> boolean greater(T firstElement, T secondElement) {
    return firstElement.compareTo(secondElement) > 0;
}

These helpers from SortUtils keep findMin and findMax easy to read. They compare two elements with compareTo, so the search for the range works for any type that implements Comparable.

Running it

1
2
3
4
Double[] numbers = {0.42, 0.32, 0.73, 0.25, 0.91, 0.05, 0.58, 0.19};
new BucketSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0.05, 0.19, 0.25, 0.32, 0.42, 0.58, 0.73, 0.91]

Create a BucketSort, pass it an array, and the same array comes back sorted. Uniform values between 0 and 1 are the classic input for Bucket Sort; with eight values, the code uses a single bucket.

Summary

  • Bucket Sort is a distribution sort: it spreads the values over buckets by where they lie in the range, sorts each bucket, and joins the buckets in order.
  • This implementation uses one ArrayList bucket per ten values, a hash that maps each value to its bucket, and Collections.sort for each bucket.
  • After the distribution, every value in a bucket is smaller than or equal to every value in the next bucket, so sorting each bucket sorts the whole array.
  • It runs in $O(n + k)$ on evenly spread data and $O(n \log n)$ when everything lands in one bucket, needs $O(n + k)$ extra space, and is stable but not in place.
  • The Java hash uses compareTo as a distance, so the buckets don’t spread the values. For integers in a small range, Counting Sort is the simpler linear-time choice; for general objects, use Arrays.sort().
This post is licensed under CC BY 4.0 by the author.