Shell Sort in Java
Learn how Shell 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
Shell Sort is a comparison sort that improves on insertion sort. Insertion sort moves values only one position at a time, so a small value near the end needs many steps to reach the front. Shell Sort first sorts values that are far apart, which lets them jump long distances early, and then sorts with smaller and smaller distances, ending with a plain insertion sort.
Three ideas carry the whole algorithm:
- Gap: the distance between the values that are compared. Each pass uses a smaller gap, and the last pass always uses a gap of 1.
- Gap insertion sort: an insertion sort on each group of values that are
gappositions apart. After the pass, the array is h-sorted: every group of valuesgapapart is in order. - Gap sequence: the list of gaps to use. This implementation uses Knuth’s sequence 1, 4, 13, 40, 121, …, where each gap is three times the previous one plus one.
Donald Shell published the algorithm in 1959, and it was one of the first sorts to beat the $O(n^2)$ barrier of the simple sorts. It sorts in place, needs no recursion and very little code, which makes it a good choice for embedded systems and small arrays. The bzip2 compressor and the qsort of the uClibc C library both use it.
This article uses Shell Sort with the Knuth gap sequence: the largest gap below a third of the array length, divided by three on every pass, down to 1.
Performance Characteristics
How fast Shell Sort runs depends mostly on the gap sequence, and the exact complexity of many sequences is still an open problem; for Knuth’s sequence the bounds below are known.
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 pass only compares, with no shifts |
| Average | about $O(n^{1.25})$ | Random input, measured in practice for Knuth’s sequence |
| Worst | $O(n^{3/2})$ | Proven upper bound for Knuth’s sequence |
Why less than $n^2$? The early passes, with large gaps, are insertion sorts on short groups, so they are cheap, and they move values most of the way to their place. Each later pass then starts from an array that is nearly sorted, and insertion sort is fast on nearly sorted data. On sorted input, each of the about $\log_3 n$ passes makes one comparison per value, which gives the $O(n \log n)$ best case.
The gap sequence matters more than anything else. Shell’s original sequence, $n/2, n/4, \ldots, 1$, has an $O(n^2)$ worst case, because values at even and odd positions never meet until the last pass. Knuth’s sequence avoids that, and sequences by Sedgewick or Ciura are faster still.
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)$: one temporary value and a few indices |
| In place | Yes |
| Stable | No (a long jump can move a value past an equal value in another group) |
Algorithm (Pseudo Code)
Shell Sort starts by choosing a gap. For ten values the gap is 4, so the first pass looks at the values at indices 0, 4 and 8 as one group, at 1, 5 and 9 as another, and so on. Each value, in turn, is taken out and compared with the value gap positions to its left. While that value is larger, it moves gap positions to the right, and the comparison repeats further left. When a smaller or equal value is found, or the start of the array is reached, the value is put down in the gap.
When the pass is done, every group is sorted. The gap is then divided by three and the pass runs again with the smaller gap, until it runs with a gap of 1, which is a plain insertion sort. By then the values are close to their final positions, so this last pass does little work, and when it ends the array is sorted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
sort(array):
gap = 1
while gap < n / 3:
gap = 3 * gap + 1
while gap > 0:
performGapInsertionSort(array, gap)
gap = gap / 3
performGapInsertionSort(array, gap):
for i = gap to n - 1:
temp = array[i]
j = i
while j >= gap and temp < array[j - gap]:
array[j] = array[j - gap]
j -= gap
array[j] = temp
After the pass with gap h, the array is h-sorted: for every index i, array[i] <= array[i + h].
An h-sorted array stays h-sorted when a later pass k-sorts it with a smaller gap. That is why the earlier passes are not wasted: each pass keeps the order the previous ones created, and the final gap-1 pass only has to clean up.
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 value being placed above the gap it may go into, the pointers 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, the positiontempwas taken from, and J isj, the position of the gap wheretempmay go. - Group: during the gap-4 pass, the values in the same group as
i(4 positions apart) stay fully visible, and the others fade out. - Colours:
tempand the value it is compared with are amber, a value being shifted ortempbeing placed is salmon, and during the last pass, with gap 1, the sorted part on the left is green. - Gap: the dashed cell is where
tempwill go if it stops now, and the footer shows the currentgap.
Java Code
The implementation is a ShellSort class with one public method, sort, and three private methods: calculateInitialGap finds the first gap in Knuth’s sequence, calculateNextGap moves to the next smaller gap, and performGapInsertionSort does one pass of insertion sort with a given gap. One small helper, less, lives in a separate SortUtils class.
The complete code is in the algorithm-examples repository on GitHub:
ShellSort.java, with the helpers inSortUtils.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;
}
int gap = calculateInitialGap(array.length);
while (gap > 0) {
performGapInsertionSort(array, gap);
gap = calculateNextGap(gap);
}
return array;
}
sort is the entry point. It accepts an array of any Comparable type, such as Integer or String. It finds the first gap, then runs one gap insertion sort per gap, dividing the gap by three after each pass, until it reaches 0. Because the last gap before 0 is always 1, the final pass is a full insertion sort, which guarantees the result is sorted. The array is sorted in place and returned.
calculateInitialGap and calculateNextGap
1
2
3
4
5
6
7
8
9
10
11
private int calculateInitialGap(final int length) {
int gap = 1;
while (gap < length / 3) {
gap = 3 * gap + 1;
}
return gap;
}
private int calculateNextGap(final int currentGap) {
return currentGap / 3;
}
calculateInitialGap walks up Knuth’s sequence, 1, 4, 13, 40, …, and stops at the first gap that is not below a third of the length. For 10 values that is 4, for 100 values 40, and for 1,000 values 364. calculateNextGap walks back down: integer division by three turns 364 into 121, 40, 13, 4 and 1, exactly the earlier terms of the sequence, and then 0, which ends the loop.
performGapInsertionSort
1
2
3
4
5
6
7
8
9
10
private <T extends Comparable<T>> void performGapInsertionSort(final T[] array, final int gap) {
for (int i = gap; i < array.length; i++) {
T temp = array[i];
int j;
for (j = i; j >= gap && SortUtils.less(temp, array[j - gap]); j -= gap) {
array[j] = array[j - gap];
}
array[j] = temp;
}
}
performGapInsertionSort is an insertion sort in which every step is gap positions instead of one. Each value from index gap onwards is taken out as temp. The inner loop compares it with the value gap positions to the left, and while that value is larger, moves it gap positions to the right. When the loop stops, temp goes into the free position at j.
Two details are worth noticing:
- The outer loop doesn’t sort one group at a time. It walks through the whole array once, and consecutive values of
ibelong to different groups, so all groups are sorted side by side in a single pass. - With
gap = 1, the method is exactly the insertion sort from the Insertion Sort guide, and like it, it movestemponly past values that are strictly larger.
less
1
2
3
public static <T extends Comparable<T>> boolean less(T firstElement, T secondElement) {
return firstElement.compareTo(secondElement) < 0;
}
This helper from SortUtils keeps the inner loop easy to read. 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 ShellSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a ShellSort, pass it an array, and the same array comes back sorted. With ten values the gaps are 4 and 1, so the sort makes two passes. The array holds Integer, not int, because the method works with Comparable objects.
Summary
- Shell Sort is an improved insertion sort: it sorts values that are far apart first, using a gap that shrinks on every pass.
- This implementation uses Knuth’s gap sequence (1, 4, 13, 40, …), starting with the largest gap below a third of the length and dividing by three after each pass.
- After the pass with gap
h, the array is h-sorted, and the final pass with gap 1 is a plain insertion sort that finishes the job. - It runs in about $O(n^{1.25})$ on average and $O(n^{3/2})$ in the worst case, needs only $O(1)$ extra space, and sorts in place but is not stable.
- Use it when memory is tight, recursion is not an option, or the code must stay small. For large arrays, $O(n \log n)$ sorts such as merge sort, heap sort or
Arrays.sort()are faster.
