Flash Sort in Java
Learn how Flash 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
Flash Sort is a distribution sort that works almost entirely in place. It estimates where each value belongs from where it lies between the minimum and the maximum, moves every value into its class, a block of the array for one slice of that range, and then finishes with a quick insertion sort, because by then every value is already close to its place.
Three ideas carry the whole algorithm:
- Classification: a value’s class is $\lfloor c_1 \cdot (value - min) \rfloor$, where $c_1 = (m - 1) / (max - min)$ scales the range to the classes $0$ to $m - 1$. The number of classes $m$ is a fraction of $n$, here 45 %.
- Permutation in cycles: after counting the classes, each value is moved directly into the next free slot of its class. The value it displaces is picked up, the flash, and moved to its own class in turn, so the array is rearranged in place, cycle by cycle.
- Insertion sort to finish: after the permutation, the classes are in order, and only the values inside each class may be out of order, a short distance from their places. Insertion sort is very fast on such nearly sorted data.
Karl-Dietrich Neubert published Flash Sort in 1998. On uniformly distributed data it runs in linear time while using only a small extra array of class counters, so it is a distribution sort that, unlike Bucket Sort, doesn’t need room for a second copy of the data.
This article explains Flash Sort with value-based classes and a classification ratio of 0.45. The Java code in the repository calculates its classes with compareTo, which changes how it behaves; the Java section shows the difference.
Performance Characteristics
Flash Sort is linear when the values are spread evenly over their range, because then each class holds only a couple of values and the final insertion sort has almost nothing to do.
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)$ | Uniformly spread values: every class is small, so insertion sort only makes short moves |
| Average | $O(n)$ | Roughly uniform data |
| Worst | $O(n^2)$ | Skewed data where most values share one class, as with the compareTo classes in the Java code |
Why can it be linear? Finding the minimum and maximum, counting the classes, building the start positions and permuting each take one pass over the array or the classes: $O(n + m)$. The final insertion sort costs as much as the distance values have to move, and when each class holds only a few values, that is $O(n)$ in total. With the repository code’s ratio, 10,000 values in 4,500 classes need about 15,600 comparisons in the insertion sort; if all values end up in one class, insertion sort makes about $n^2 / 4$ comparisons instead.
Flash Sort is sensitive to the distribution of the data. A few extreme values stretch the range and squeeze everything else into a handful of classes. A common improvement is to sort each large class recursively with Flash Sort instead of insertion sort, which limits the damage.
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(m)$: the class counters, about $0.45n$ integers; the values themselves are moved in place |
| In place | Mostly (only the small array of class counters is extra) |
| Stable | No (the permutation cycles move values past equal values) |
Algorithm (Pseudo Code)
Flash Sort starts by finding the smallest and largest value and choosing the number of classes. In one pass it computes each value’s class and counts how many values fall into each class. Turning the counts into running totals gives, for every class, the position just after the last slot it will occupy.
The permutation then walks the array. It picks up a value that is not yet in its class, the flash, and drops it into the last free slot of its class, which lowers that class’s free position by one. The value that was in that slot becomes the new flash, and the process repeats until a value lands back in the slot where the cycle started. When every value has been moved, the classes are in order from left to right. A final insertion sort sorts the values inside each class, and the array is sorted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
flashSort(arr):
min = smallest value, max = largest value
if max == min: return
m = max(1, (int) (0.45 * n))
c1 = (m - 1) / (max - min)
for each value: L[(int) (c1 * (value - min))]++ // classify
for k = 1 to m - 1: L[k] += L[k - 1] // transform: end of each class
move = 0, j = 0, k = m - 1 // permute
while move < n - 1:
while j > L[k] - 1: // find a value not yet in its class
j++, k = class of arr[j]
flash = arr[j]
while j != L[k]:
k = class of flash
swap flash with arr[L[k] - 1]
L[k]--, move++
insertionSort(arr)
After the permutation, every value of class k lies before every value of class k + 1, so insertion sort only has to sort within classes.
The test
j > L[k] - 1checks whether positionjis already in the filled part of its class.L[k]always points just past the free slots of classk, so oncejhas passedL[k] - 1, the value atjwas put there by the permutation and must be skipped.
Visualization
The visualization below follows the algorithm step by step, starting with the values 0 to 9 in shuffled order.
By default it classifies by value, as in the pseudo code, with $m = 4$ classes for ten values. Tick Use compareTo to see the Java code’s version, where every value except the minimum lands in the last class.
Each step shows the array, the flash being carried, the class counters 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.
- Classes: the small number in each cell is the class of its value. The classes row shows the counters: counts during classification, and the next free position of each class during the permutation.
- Flash: the cell on the left of the top row is the value being carried during a cycle. J marks where the current cycle started. As in the Java code, the value at J stays where it is until the cycle closes, so for a while it can appear twice: once at J and once in its class.
- Colours: the value being classified, or the cycle’s start, is amber; the value just placed, or just inserted, is salmon; and sorted values are green.
- Phase: the footer shows the phase, and during the final insertion sort, the number of comparisons.
Java Code
The implementation is a FlashSort class with one public method, sort, two constructors and a getter and setter for the classification ratio. The private methods follow the phases: flashSort drives the algorithm, findMin and findMaxIndex find the range, classify counts the classes, transform turns the counts into positions, permute moves the values into their classes, and insertionSort finishes. The class doesn’t use the SortUtils helpers.
The complete code is in the algorithm-examples repository on GitHub:
FlashSort.java.
Constructors and classification ratio
1
2
3
4
5
6
7
8
9
10
11
private double classificationRatio = 0.45;
public FlashSort() {
}
public FlashSort(double classificationRatio) {
if (classificationRatio <= 0 || classificationRatio >= 1) {
throw new IllegalArgumentException("Classification ratio must be between 0 and 1 (exclusive).");
}
this.classificationRatio = classificationRatio;
}
The classification ratio sets the number of classes as a fraction of the array length. The default, 0.45, gives enough classes that each holds about two values on uniform data, which keeps the final insertion sort short, while the counter array stays at less than half the size of the input. The second constructor and setClassificationRatio accept any ratio strictly between 0 and 1.
sort and flashSort
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) {
flashSort(array);
return array;
}
private <T extends Comparable<? super T>> void flashSort(T[] arr) {
if (arr.length == 0) {
return;
}
final T min = findMin(arr);
final int maxIndex = findMaxIndex(arr);
if (arr[maxIndex].compareTo(min) == 0) {
return;
}
final int m = Math.max(1, (int) (classificationRatio * arr.length));
final int[] classificationArray = new int[m];
final double c1 = (double) (m - 1) / arr[maxIndex].compareTo(min);
classify(arr, classificationArray, c1, min);
transform(classificationArray);
permute(arr, classificationArray, c1, min, arr.length, m);
insertionSort(arr);
}
sort hands the array to flashSort and returns it, sorted in place. flashSort returns early for an empty array, or when the largest value equals the smallest, since then every value is equal. It sets the number of classes m, with at least one class so that tiny arrays still work, computes the scale factor c1, and runs the four phases.
c1divides bymax.compareTo(min), and the classes are computed fromvalue.compareTo(min). That treatscompareToas the distance between two values, but theComparablecontract only promises its sign. ForInteger,max.compareTo(min)is 1, soc1 = m - 1, andc1 * value.compareTo(min)is 0 for the minimum andm - 1for every other value. All values but the minimum share the last class, the permutation does almost nothing, and the final insertion sort does all the work: with the repository code, 10,000 random integers take about 25 million comparisons, roughly $n^2 / 4$, where value-based classes need about 15,600 in the insertion sort. 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 insertion sort cleans up. A working version needs a numeric key and the differencekey(value) - key(min).
findMin and findMaxIndex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private <T extends Comparable<? super T>> T findMin(final T[] arr) {
T min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i].compareTo(min) < 0) {
min = arr[i];
}
}
return min;
}
private <T extends Comparable<? super T>> int findMaxIndex(final T[] arr) {
int maxIndex = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i].compareTo(arr[maxIndex]) > 0) {
maxIndex = i;
}
}
return maxIndex;
}
findMin returns the smallest value, and findMaxIndex the index of the largest one. Neubert’s original version moves the maximum to the front before permuting, which is why it tracks an index; this version only uses the index to read the maximum.
classify and transform
1
2
3
4
5
6
7
8
9
10
11
12
private <T extends Comparable<? super T>> void classify(final T[] arr, final int[] classificationArray, final double c1, final T min) {
for (int i = 0; i < arr.length; i++) {
int k = (int) (c1 * arr[i].compareTo(min));
classificationArray[k]++;
}
}
private void transform(final int[] classificationArray) {
for (int i = 1; i < classificationArray.length; i++) {
classificationArray[i] += classificationArray[i - 1];
}
}
classify computes each value’s class and counts how many values each class gets. transform turns the counts into running totals in place, so classificationArray[k] becomes the position just after the last slot of class k. The permutation fills each class from there backwards.
permute
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private <T extends Comparable<? super T>> void permute(final T[] arr, final int[] classificationArray, final double c1, T min, int n, int m) {
int move = 0;
int j = 0;
int k = m - 1;
T flash;
while (move < n - 1) {
while (j > classificationArray[k] - 1) {
j++;
k = (int) (c1 * arr[j].compareTo(min));
}
flash = arr[j];
while (j != classificationArray[k]) {
k = (int) (c1 * flash.compareTo(min));
T temp = arr[classificationArray[k] - 1];
arr[classificationArray[k] - 1] = flash;
flash = temp;
classificationArray[k]--;
move++;
}
}
}
permute is the heart of Flash Sort. The outer loop runs until n - 1 values have been moved; the last one then has to be in place. The first inner loop moves j forward past positions that already hold their final class, and picks up the first value that doesn’t as the flash. The second inner loop follows the cycle: it puts the flash into the last free slot of its class, lowers that class’s counter, and picks up the value it displaced. The cycle ends when a value is put into slot j itself, where the cycle began.
Two details are worth noticing:
- Each value is moved exactly once, directly to its class, so the permutation is $O(n)$ moves, using only the one
flashvariable as extra storage. - The initial
k = m - 1makes the first inner loop stop atj = 0straight away: before any moves,classificationArray[m - 1]isn, so0 > n - 1is false.
insertionSort
1
2
3
4
5
6
7
8
9
10
11
12
private <T extends Comparable<? super T>> void insertionSort(final T[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
T key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j].compareTo(key) > 0) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
insertionSort runs over the whole array once the classes are in place. Values never have to leave their class, because every value of a later class is larger, so each key only shifts past the few values before it in its own class. The Insertion Sort guide explains the method step by step.
Running it
1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new FlashSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a FlashSort, pass it an array, and the same array comes back sorted. The array holds Integer, not int, because the method works with Comparable objects.
Summary
- Flash Sort is an in-place distribution sort: it classifies values by where they lie in the range, permutes them into their classes in cycles, and finishes with insertion sort.
- This implementation uses about $0.45n$ classes, turns the class counts into end positions, and moves each value once, carrying the displaced value along as the flash.
- After the permutation, the classes are in order, so insertion sort only has to sort within each class.
- With value-based classes it runs in $O(n)$ on uniform data and $O(n^2)$ on badly skewed data, needs $O(m)$ extra space, and is not stable.
- The Java code’s
compareTo-based classes put nearly every value in one class, which leaves all the work to insertion sort. For real data, useArrays.sort(), or a correctly keyed Flash Sort when the values are numeric and evenly spread.
