Comb Sort in Java
Learn how Comb 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
Comb Sort is a comparison sort that improves on bubble sort. Bubble sort only compares neighbours, so a small value near the end, a turtle, crawls to the front one position per pass. Comb Sort compares values that are a gap apart, so a turtle can jump many positions at once. The gap shrinks after every pass until it reaches 1, and the last passes are plain bubble sort passes on an array that is already nearly sorted.
Three ideas carry the whole algorithm:
- Gap: the distance between the two values that are compared. It starts at the length of the array.
- Shrink factor: after every pass the gap is divided by 1.3 and rounded down, which was found to work best in practice.
- Final gap-1 passes: once the gap is 1, passes repeat until one makes no swaps, exactly like bubble sort with a
swappedflag.
Włodzimierz Dobosiewicz described the idea in 1980, and Stephen Lacey and Richard Box popularised it in 1991 under the name Comb Sort, with the shrink factor of 1.3. It does for bubble sort what Shell Sort does for insertion sort: it lets values move long distances early. It sorts in place, needs only a few lines of code, and on random data it runs much faster than bubble sort.
This article uses Comb Sort with a shrink factor of 1.3: the gap is shrunk before every pass, and the sort ends after a gap-1 pass without swaps.
Performance Characteristics
Comb Sort’s speed depends on how well the large-gap passes clear out the turtles, and that depends on the input and on the shrink factor.
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 \log n)$ | An already sorted array: every gap still makes one pass, with no swaps |
| Average | close to $O(n \log n)$ in practice | Random input: the gap passes leave very little for the gap-1 passes |
| Worst | $O(n^2)$ | Inputs where the gap-1 phase still has to make many passes |
Why roughly $n \log n$? The gap shrinks by a factor of 1.3 per pass, so there are about $\log_{1.3} n$ passes before it reaches 1, and each pass makes about $n$ comparisons. On typical data, those passes move nearly every value close to its place, and only a couple of gap-1 passes remain. There is no guarantee, though: in the worst case the gap-1 phase still needs $O(n)$ passes.
A shrink factor of 1.3 is a sweet spot. A smaller factor makes more passes than needed; a larger one shrinks the gap so fast that turtles are left behind. A common refinement, “Combsort11”, replaces gaps of 9 and 10 with 11, which avoids a few bad gap sequences.
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(1)$: the gap, a flag and a loop index |
| In place | Yes |
| Stable | No (a long-gap swap can move a value past an equal value) |
Algorithm (Pseudo Code)
Comb Sort starts with a gap equal to the length of the array and shrinks it before the first pass: for ten values, the first gap is 7. A pass compares every value with the one gap positions to its right and swaps them when the right one is smaller. Small values from the end of the array jump far to the left, and large values from the front jump far to the right.
Each next pass uses a smaller gap: 5, then 3, then 2, then 1. The passes with large gaps do the rough work, and the passes with small gaps the fine work. Once the gap is 1, each pass is a bubble sort pass, and they repeat until one of them makes no swaps. Then every pair of neighbours is in order, and the array is sorted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
sort(arr):
gap = n
swapped = true
while gap != 1 or swapped:
gap = max((int) (gap / 1.3), 1)
swapped = performSwaps(arr, gap)
performSwaps(arr, gap):
swapped = false
for i = 0 to n - gap - 1:
if arr[i + gap] < arr[i]:
swap(i, i + gap)
swapped = true
return swapped
After a pass with gap g, no pair of values g apart was out of order when it was compared; after a gap-1 pass without swaps, no pair of neighbours is out of order, so the array is sorted.
The loop condition
gap != 1 || swappedkeeps going for two reasons: while the gap is larger than 1, the sort is not finished whatever happened, and once it is 1, a pass that still swapped may have left other neighbours out of order. Only a gap-1 pass with no swaps proves the array is sorted.
Visualization
The visualization below follows the Java code line by line, starting with the values 0 to 9 in shuffled order.
Each step shows the array, the pair being compared, joined by an arc, 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.
- Pointers: I is
i, and I+G isi + gap, the value it is compared with. The arc above the array joins the two. - Colours: the two values being compared are amber, or salmon when they swap, and the whole array turns green when it is sorted.
- Gap: the footer shows the current
gapand theswappedflag of the pass.
Java Code
The implementation is a CombSort class with one public method, sort, and two private methods: getNextGap shrinks the gap, and performSwaps makes one pass with a given gap. The shrink factor is the constant SHRINK_FACTOR = 1.3. Two small helpers, swap and less, live in a separate SortUtils class.
The complete code is in the algorithm-examples repository on GitHub:
CombSort.java, with the helpers inSortUtils.java.
sort
1
2
3
4
5
6
7
8
9
10
11
12
@Override
public <T extends Comparable<T>> T[] sort(T[] arr) {
int gap = arr.length;
boolean swapped = true;
while (gap != 1 || swapped) {
gap = getNextGap(gap);
swapped = performSwaps(arr, gap);
}
return arr;
}
sort is the entry point. It accepts an array of any Comparable type, starts with the gap at the length of the array and swapped set to true, so that the loop runs at least once. Each round shrinks the gap and makes one pass. The loop ends only when the gap is 1 and the pass made no swaps. The array is sorted in place and returned.
The edge cases work out without special checks: an empty array shrinks the gap from 0 to 1 and makes one pass with nothing to compare, and a one-element array makes one empty pass with gap 1. In both cases swapped ends up false and the loop stops.
getNextGap
1
2
3
4
private int getNextGap(int gap) {
gap = (int) (gap / SHRINK_FACTOR);
return Math.max(gap, 1);
}
getNextGap divides the gap by 1.3 and casts the result to an int, which rounds it down. Math.max keeps the gap from dropping to 0, so once it reaches 1, it stays at 1. For ten values, the gaps are 7, 5, 3, 2, 1, 1, …
performSwaps
1
2
3
4
5
6
7
8
9
10
11
12
private <T extends Comparable<T>> boolean performSwaps(final T[] arr, final int gap) {
boolean swapped = false;
for (int i = 0; i < arr.length - gap; i++) {
if (SortUtils.less(arr[i + gap], arr[i])) {
SortUtils.swap(arr, i, i + gap);
swapped = true;
}
}
return swapped;
}
performSwaps walks i from the start of the array to the last index that still has a partner gap positions to its right. Whenever the partner is smaller, the two swap, and swapped records that something moved. With gap = 1, the method is exactly one pass of the Bubble Sort guide.
swap and less
1
2
3
4
5
6
7
8
9
10
11
public static <T> void swap(T[] array, int i, int j) {
if (i != j) {
final T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
public static <T extends Comparable<T>> boolean less(T firstElement, T secondElement) {
return firstElement.compareTo(secondElement) < 0;
}
These helpers from SortUtils keep the pass easy to read. swap exchanges two elements, and less returns true when the first element is smaller than the second, using compareTo, so the algorithm works 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 CombSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a CombSort, pass it an array, and the same array comes back sorted, after six passes with the gaps 7, 5, 3, 2, 1 and 1. The class is package-private, so the code must be in the com.javanibble.sort package.
Summary
- Comb Sort is a bubble sort with a shrinking gap: it compares values that are a gap apart, so turtles near the end jump to the front early.
- This implementation divides the gap by a shrink factor of 1.3 before every pass, and keeps making gap-1 passes until one has no swaps.
- After a gap-1 pass without swaps, every pair of neighbours is in order, so the array is sorted.
- It is close to $O(n \log n)$ on typical data but $O(n^2)$ in the worst case, needs $O(1)$ extra space, and is in place but not stable.
- Use it as a simple, much faster replacement for bubble sort. When a guaranteed $O(n \log n)$ is needed, choose heap sort, merge sort or
Arrays.sort().
