Spread Sort in Java
Learn how Spread 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.
Introduction
Spread Sort is a hybrid distribution sort. It spreads the values of a range over a number of buckets, each covering an equal slice between the smallest and largest value, and then sorts every bucket the same way, recursively. Small buckets are finished with insertion sort.
Three ideas carry the whole algorithm:
- Spread by value: a value’s bucket is decided by where it lies between the minimum and the maximum, like in Bucket Sort, so every bucket holds smaller values than the next.
- Recursion: a bucket that is still large is spread again into its own buckets, so the values are narrowed down in a few rounds, a bit like Radix Sort going through digits.
- Insertion sort for small parts: once a segment is smaller than a threshold, spreading it further costs more than it saves, and insertion sort finishes it.
Steven J. Ross published Spread Sort in 2002 as a mix of radix sort, bucket sort and comparison sorting, and a version of it is in the Boost.Sort C++ library. On data whose values are spread fairly evenly, it needs only a few rounds of spreading and beats comparison sorts; on unfavourable data, a real implementation falls back to a comparison sort to keep its worst case reasonable.
This article explains Spread Sort with value-based bucket indices and an insertion sort threshold. The Java code in the repository calculates its bucket indices with compareTo, which changes how it behaves; the Java section shows the difference.
Performance Characteristics
Spread Sort is as fast as its buckets are even: well-spread values are sorted in a few rounds, but values that all land in one bucket need many.
Time Complexity
Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.
| Case | Time | When it happens |
|---|---|---|
| Best | $O(n)$ | The values are spread evenly, so each round shrinks the buckets by the bucket count |
| Average | $O(n \log n)$ | Typical data: a few levels of spreading, each touching every value once |
| Worst | $O(n^2)$ | Each round only splits off a few values, as with the compareTo indices in the Java code |
Why does the spread matter so much? Every level of recursion looks at every value of its segment a few times: to find the minimum and maximum, to distribute, and to copy back. If each bucket is much smaller than its segment, the levels shrink fast and the total stays close to linear. If one bucket keeps almost all the values, the next level has nearly the same amount of work, and the levels add up to $O(n^2)$.
Real Spread Sort implementations, such as Boost’s, guard against the bad case: they choose the number of buckets from the bit range of the keys and switch to a comparison sort when spreading stops making progress. That keeps the worst case at about $O(n \log n)$.
Space Complexity
Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.
| Property | Value |
|---|---|
| Space | $O(n)$ for the buckets and their copies, plus the recursion stack |
| In place | No (values are copied into buckets, and each bucket is copied again to be sorted) |
| Stable | Yes for the bucket steps; insertion sort is stable too, so equal values keep their order |
Algorithm (Pseudo Code)
Spread Sort looks at the segment it has to sort. If the segment is small, insertion sort finishes it. If all its values are equal, there is nothing to do. Otherwise it finds the smallest and largest value and creates a number of buckets, about one for every threshold values. Each value goes into the bucket for its part of the range: values near the minimum into the first bucket, values near the maximum into the last.
Then the buckets are handled in order. Each bucket is sorted by the same steps, recursively: it is either small enough for insertion sort, or it is spread again over its own buckets. The sorted bucket is copied back into the segment, right after the previous one. Because every bucket covers a higher part of the range than the one before it, the segment is sorted when the last bucket has been copied back.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
spreadSort(array, left, right):
if left >= right: return
if right - left < insertionSortThreshold:
insertionSort(array, left, right); return
min = smallest value, max = largest value
if min == max: return
numBuckets = max(segmentSize / insertionSortThreshold, minBuckets)
for each value in array[left .. right]:
bucketIndex = (value - min) * numBuckets / (max - min + 1)
buckets[bucketIndex].add(value)
index = left
for each non-empty bucket:
spreadSort(bucket) // recursively
copy the bucket into array, starting at index
After the distribution, every value in a bucket is smaller than every value in the next bucket, so sorting each bucket and copying them back in order sorts the segment.
The Java code computes
bucketIndexfromvalue.compareTo(min)andmax.compareTo(min)instead of from differences. For numbers,compareToonly returns -1, 0 or 1, so the index no longer depends on how far a value is from the minimum. The warning in thedistributeElementssection shows what that does.
Visualization
The visualization below follows the algorithm step by step, starting with the values 0 to 9 in shuffled order.
Two settings differ from the code, so that the spreading is visible on ten values. The code’s default threshold is 16, which sends any segment of up to 16 values straight to insertion sort, so the visualization starts with a threshold of 3. And it computes bucket indices from differences, as in the pseudo code; tick Use compareTo to see the Java code’s version.
Each step shows the segment being sorted, its 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.
- Level: the line at the top shows where the recursion is:
arrayfor the whole array,array › bucket 0for the copy of bucket 0, and so on. Each level sorts its own copy and hands it back. - Buckets: the rows below the segment are its buckets. The bucket being filled, sorted or copied back is outlined.
- Colours: the value being distributed is amber, the value just added or the values just copied back are salmon, and sorted values are green.
- Settings: choose the threshold, 3 or the code’s 16, and tick Use compareTo to distribute as the Java code does. The footer shows the current recursion depth.
Java Code
The implementation is a SpreadSort class with one public method, sort, and two constructors: the default one uses an insertion sort threshold of 16, an initial bucket capacity of 16 and at least 2 buckets, and the other accepts custom values within checked limits. The private methods split up the work: spreadSort is the recursive core, findMin and findMax find the range, calculateNumBuckets and createBuckets set up the buckets, distributeElements fills them, collectElements sorts and copies them back, and insertionSort handles small segments. A small nested class, Bucket, is a growable array. Two helpers, less and greater, live in a separate SortUtils class.
The complete code is in the algorithm-examples repository on GitHub:
SpreadSort.java, with the helpers inSortUtils.java.
Constructors
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public SpreadSort(int insertionSortThreshold, int initialBucketCapacity, int minBuckets) {
if (insertionSortThreshold < 1 || insertionSortThreshold > MAX_INSERTION_SORT_THRESHOLD) {
throw new IllegalArgumentException("Insertion sort threshold must be between 1 and " + MAX_INSERTION_SORT_THRESHOLD);
}
if (initialBucketCapacity < 1 || initialBucketCapacity > MAX_INITIAL_BUCKET_CAPACITY) {
throw new IllegalArgumentException("Initial bucket capacity must be between 1 and " + MAX_INITIAL_BUCKET_CAPACITY);
}
if (minBuckets < 1 || minBuckets > MAX_MIN_BUCKETS) {
throw new IllegalArgumentException("Minimum number of buckets must be between 1 and " + MAX_MIN_BUCKETS);
}
this.insertionSortThreshold = insertionSortThreshold;
this.initialBucketCapacity = initialBucketCapacity;
this.minBuckets = minBuckets;
}
public SpreadSort() {
this(16, 16, 2);
}
The three settings tune the algorithm: insertionSortThreshold decides when a segment is small enough for insertion sort and also how many buckets a segment gets, initialBucketCapacity sets the starting size of each bucket’s array, and minBuckets is the smallest number of buckets to spread into. The constructor rejects values outside 1 to 1,000, 1 to 1,000 and 1 to 100.
sort and spreadSort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
if (array.length == 0) {
return array;
}
spreadSort(array, 0, array.length - 1);
return array;
}
private <T extends Comparable<T>> void spreadSort(final T[] array, final int left, final int right) {
if (left >= right) {
return;
}
if (right - left < insertionSortThreshold) {
insertionSort(array, left, right);
return;
}
T min = findMin(array, left, right);
T max = findMax(array, left, right);
if (min.equals(max)) {
return;
}
int numBuckets = calculateNumBuckets(right - left + 1);
final Bucket<T>[] buckets = createBuckets(numBuckets);
distributeElements(array, left, right, min, max, numBuckets, buckets);
collectElements(array, left, buckets);
}
sort returns an empty array straight back and otherwise sorts the whole array in place. spreadSort sorts array[left .. right]: small segments go to insertion sort, and a segment whose smallest and largest values are equal is already sorted. Otherwise it sets up the buckets, distributes the values and collects them back.
findMin, findMax and calculateNumBuckets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private <T extends Comparable<T>> T findMin(final T[] array, final int left, final int right) {
T min = array[left];
for (int i = left + 1; i <= right; i++) {
if (SortUtils.less(array[i], min)) {
min = array[i];
}
}
return min;
}
private <T extends Comparable<T>> T findMax(final T[] array, final int left, final int right) {
T max = array[left];
for (int i = left + 1; i <= right; i++) {
if (SortUtils.greater(array[i], max)) {
max = array[i];
}
}
return max;
}
private int calculateNumBuckets(final int segmentSize) {
int numBuckets = segmentSize / insertionSortThreshold;
return Math.max(numBuckets, minBuckets);
}
findMin and findMax each walk the segment once and keep the smallest or largest value seen. calculateNumBuckets aims for buckets of about insertionSortThreshold values each, so that one more round of spreading would leave them small enough for insertion sort, with at least minBuckets buckets.
distributeElements
1
2
3
4
5
6
7
8
private <T extends Comparable<T>> void distributeElements(final T[] array, final int left, final int right, final T min, final T max, final int numBuckets, final Bucket<T>[] buckets) {
final double range = max.compareTo(min);
for (int i = left; i <= right; i++) {
final int scaleRangeDifference = array[i].compareTo(min) * numBuckets;
int bucketIndex = (int) (scaleRangeDifference / (range + 1));
buckets[bucketIndex].add(array[i]);
}
}
distributeElements is meant to scale each value’s distance from the minimum to a bucket index between 0 and numBuckets - 1. Dividing by range + 1 keeps the index of the maximum below numBuckets.
compareTois used as if it returned the distance between two values, but theComparablecontract only promises its sign. ForInteger,rangeis always 1 andarray[i].compareTo(min)is 0 or 1, so the minimum goes to bucket 0 and every other value goes to bucketnumBuckets / 2. Each level of recursion then only splits off the minimum, which makes the sort quadratic and its recursion as deep as the array is long: with the repository code, 10,000 random integers take about half a second, and 30,000 throw aStackOverflowError. ForString,compareToreturns character differences, and 20 strings such as"aa","az"and"b"throw anArrayIndexOutOfBoundsException. The array is still sorted correctly whenever the method finishes, because the buckets stay in order, but the spreading does no useful work. A working version needs a numeric key, such as theintvalue itself, and the differencekey(value) - key(min).
collectElements
1
2
3
4
5
6
7
8
9
10
11
12
private <T extends Comparable<T>> void collectElements(final T[] array, final int left, final Bucket<T>[] buckets) {
int index = left;
for (Bucket<T> bucket : buckets) {
if (bucket.size() > 0) {
T[] bucketArray = bucket.toArray();
spreadSort(bucketArray, 0, bucketArray.length - 1);
for (T element : bucketArray) {
array[index++] = element;
}
}
}
}
collectElements visits the buckets in order. Each non-empty bucket is copied into an array of exactly its size, sorted with spreadSort, which is where the recursion happens, and copied back into the segment from index onwards. Each level of recursion therefore works on its own copy, and the values are written back only once that copy is sorted.
insertionSort
1
2
3
4
5
6
7
8
9
10
11
private <T extends Comparable<T>> void insertionSort(final T[] array, final int left, final int right) {
for (int i = left + 1; i <= right; i++) {
T key = array[i];
int j = i - 1;
while (j >= left && SortUtils.greater(array[j], key)) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = key;
}
}
insertionSort finishes segments smaller than the threshold. Each value from left + 1 onwards is taken out as the key, larger values before it shift one position right, and the key drops into the gap. The Insertion Sort guide explains it step by step.
Bucket
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private static class Bucket<T extends Comparable<T>> {
private T[] elements;
private int size;
Bucket(int initialBucketCapacity) {
elements = (T[]) new Comparable[initialBucketCapacity];
size = 0;
}
void add(T element) {
if (size == elements.length) {
elements = Arrays.copyOf(elements, size * 2);
}
elements[size++] = element;
}
int size() {
return size;
}
T[] toArray() {
return Arrays.copyOf(elements, size);
}
}
Bucket is a minimal growable array, like a stripped-down ArrayList: add doubles the backing array when it is full, and toArray returns a copy trimmed to the number of elements. It exists so that buckets can hold a generic T[] without the overhead of a full list.
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 are used by findMin, findMax and insertionSort. They compare two elements with compareTo, so those parts of the algorithm work for any type that implements Comparable.
Running it
1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new SpreadSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a SpreadSort, pass it an array, and the same array comes back sorted. With the default threshold of 16, ten values are sorted by insertion sort alone; use new SpreadSort(3, 16, 2) to make the spreading happen.
Summary
- Spread Sort is a hybrid distribution sort: it spreads a segment’s values over buckets by range, sorts each bucket recursively, and finishes small segments with insertion sort.
- This implementation chooses about one bucket per
insertionSortThresholdvalues, sorts each bucket as a separate copy, and copies the sorted buckets back in order. - Every bucket holds smaller values than the next, so sorting the buckets and joining them sorts the segment.
- With a value-based spread it runs in close to $O(n)$ on even data and $O(n \log n)$ typically, needs $O(n)$ extra space, and is stable but not in place.
- The Java code’s
compareTo-based bucket index splits off only the minimum each round, making it $O(n^2)$ with deep recursion; for real data, useArrays.sort()or a properly keyed Radix Sort.
