Shell Sort is an optimized version of Insertion Sort. It improves upon the basic insertion sort by allowing the exchange of far-apart elements, which helps reduce large-scale disorder faster. Named after its inventor Donald Shell, this algorithm is especially useful for medium-sized arrays.
Shell Sort works by sorting elements that are a certain gap apart, then progressively reducing the gap until it becomes 1 (at which point it finishes with a final insertion sort).
n/2
) and perform a gapped insertion sort.By moving elements over large gaps early on, Shell Sort drastically reduces the total number of swaps needed in the later stages.
Case | Time Complexity |
---|---|
Best | O(n log n) |
Average | O(n^3/2) or better |
Worst | O(n²) (depends on gap sequence) |
Shell Sort’s performance heavily depends on the gap sequence used. Common sequences include:
n/2, n/4, ..., 1
#include <iostream>
using namespace std;
void shellSort(int arr[], int n) {
// Start with a large gap, reduce it each iteration
for (int gap = n / 2; gap > 0; gap /= 2) {
// Perform gapped insertion sort for this gap
for (int i = gap; i < n; i++) {
int temp = arr[i];
int j;
// Shift earlier elements until the right position for arr[i]
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
arr[j] = arr[j - gap];
}
// Place temp at its correct location
arr[j] = temp;
}
// Print array after each gap reduction
cout << "After gap " << gap << ": ";
for (int k = 0; k < n; k++) cout << arr[k] << " ";
cout << endl;
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
int main() {
int arr[] = {23, 12, 1, 8, 34, 54, 2, 3};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array:\n";
printArray(arr, n);
shellSort(arr, n);
cout << "Sorted array:\n";
printArray(arr, n);
return 0;
}
Original array:
23 12 1 8 34 54 2 3
After gap 4: 3 12 1 8 23 54 2 34
After gap 2: 1 2 3 8 23 12 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 elements 4 apart:
After inserting:
[3, 12, 1, 8, 23, 54, 2, 34]
Compare elements 2 apart:
After inserting:
[1, 2, 3, 8, 23, 12, 34, 54]
Now it works like regular Insertion Sort, but the array is mostly sorted already.
[1, 2, 3, 8, 12, 23, 34, 54]
[1, 2, 3, 8, 12, 23, 34, 54]