Shell Sort is an in-place comparison sort that generalizes Insertion Sort by allowing the exchange of items that are far apart. It improves performance by comparing and sorting elements at a defined gap (also called interval or stride), which decreases over time until the gap is 1 — effectively ending with a standard Insertion Sort.
Shell Sort is named after Donald Shell, who introduced it in 1959.
gap distance apart using Insertion Sort logic.Each pass moves elements closer to their correct position, so the final Insertion Sort becomes very efficient.
| Gap Sequence | Best | Average | Worst |
|---|---|---|---|
| Shell’s original gap | O(n log²n) | O(n log²n) | O(n²) |
| Hibbard/Sedgewick | O(n log n) | O(n log^1.5 n) | O(n^(4/3)) or less |
public class ShellSortExample {
public static void shellSort(int[] arr) {
int n = arr.length;
// Start with a large gap, then reduce the gap
for (int gap = n / 2; gap > 0; gap /= 2) {
// Perform a gapped insertion sort for this gap size
for (int i = gap; i < n; i++) {
int temp = arr[i];
int j;
// Shift earlier gap-sorted elements up until correct location for arr[i] is found
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
arr[j] = arr[j - gap];
}
// Put temp (original arr[i]) in its correct location
arr[j] = temp;
}
// Print after each pass
System.out.print("After gap " + gap + ": ");
printArray(arr);
}
}
public static void printArray(int[] arr) {
for (int value : arr) {
System.out.print(value + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {23, 12, 1, 8, 34, 54, 2, 3};
System.out.println("Original array:");
printArray(arr);
shellSort(arr);
System.out.println("Sorted array:");
printArray(arr);
}
}
Original array:
23 12 1 8 34 54 2 3
After gap 4: 23 3 1 8 2 54 12 34
After gap 2: 1 3 2 8 12 23 34 54
After gap 1: 1 2 3 8 12 23 34 54
Sorted array:
1 2 3 8 12 23 34 54
Let’s sort:
[23, 12, 1, 8, 34, 54, 2, 3]
Compare and sort elements that are 4 positions apart:
After pass:
[23, 3, 1, 8, 2, 54, 12, 34]
Now compare elements 2 apart:
Array becomes:
[1, 3, 2, 8, 12, 54, 23, 34]
→ refined again →
[1, 3, 2, 8, 12, 23, 34, 54]
Final Insertion Sort-like pass:
[1, 2, 3, 8, 12, 23, 34, 54]
[1, 2, 3, 8, 12, 23, 34, 54]