Shell sort generalizes insertion sort by comparing and shifting elements that are gap positions apart. It starts with a large gap (n/2) and halves it until the gap is 1, at which point the array is nearly sorted and the final insertion pass is cheap. Complexity depends on the gap sequence; with n/2 it is O(n^2) worst case but often much faster in practice. It is in place and not stable.
Remember
for (gap = n / 2; gap > 0; gap /= 2)
for (i = gap; i < n; i++) {
key = a[i]; j = i;
while (j >= gap && a[j - gap] > key) { a[j] = a[j - gap]; j -= gap; }
a[j] = key;
}
Reference
Cheat Sheet
Keep these facts handy while you work with Shell Sort in C.
Topic
Detail
Gap sequence
n/2, n/4, ..., 1
Space
O(1)
Stable
No
Worst (n/2 gaps)
O(n^2)
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Counting Sort.
Example 1 — Show the array after each gap
Sort 12, 34, 54, 2, 3.
C
#include <stdio.h>
int main(void) {
int a[] = {12, 34, 54, 2, 3};
int n = 5;
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int key = a[i], j = i;
while (j >= gap && a[j - gap] > key) {
a[j] = a[j - gap];
j -= gap;
}
a[j] = key;
}
printf("gap %d:", gap);
for (int k = 0; k < n; k++) printf(" %d", a[k]);
printf("\n");
}
return 0;
}
Output
gap 2: 3 2 12 34 54
gap 1: 2 3 12 34 54
How It Works
With gap 2, 3 and 2 travel far toward the front in a few moves.
The array is almost sorted after gap 2.
The gap 1 pass is plain insertion sort and only swaps 3 and 2.
Edge Cases & Pitfalls
Check these before relying on Shell Sort in real programs.
gap
Last gap must be 1
If the final gap is not 1 the array may remain partly unsorted.
seq
Poor gap sequences
Halving is simple but not optimal; Knuth or Ciura sequences perform better.
Remember
Key Takeaways
Insertion sort with gaps.
Final gap is 1.
Sequence controls speed.
One line: Shell sort generalizes insertion sort by comparing and shifting elements that are gap positions apart.
Frequently Asked Questions
It moves elements long distances early, so the final insertion pass works on nearly sorted data.
It depends on the gap sequence; between O(n log^2 n) and O(n^2), with about O(n^2) for simple halving.
Continue with "C Counting Sort" next. Count occurrences of small integer keys and rebuild the array. The C Sorting Algorithms hub lists every topic in order.