Shellsort — Definition, Formula & Example
Shellsort is a sorting algorithm that compares and moves elements that sit far apart in a list, then repeats with smaller and smaller gaps. The last pass uses a gap of 1, which is ordinary insertion sort, so the list ends up fully sorted.
An array is -sorted if for every valid index . Shellsort takes a decreasing gap sequence . For each gap , it insertion-sorts the interleaved subsequences for . A -sort never undoes an earlier -sort, so each pass keeps the order the previous passes built. The final 1-sort guarantees a sorted array. Shellsort sorts in place and is not stable.
Key Formula
Where:
- = The k-th gap in Knuth's sequence. Use the gaps from largest to smallest, starting with the largest gap less than about n/3, where n is the list length.
- = Position in the gap sequence. The gap k = 1 gives h = 1, the final insertion-sort pass.
Worked Example
Problem: Sort the list [9, 8, 3, 7, 5, 6, 4, 1] with Shellsort, using the gaps 4, 2, 1. Count the shifts each pass makes, where a shift moves one element one slot within its subsequence.
Step 1: Gap 4: split the list into 4 pairs of positions 4 apart and sort each pair. (9,5) becomes (5,9), (8,6) becomes (6,8), (3,4) is already in order, and (7,1) becomes (1,7). That is 3 shifts.
Step 2: Gap 2: the even positions hold 5, 3, 9, 4, which sort to 3, 4, 5, 9 with 3 shifts. The odd positions hold 6, 1, 8, 7, which sort to 1, 6, 7, 8 with 2 shifts. Interleave the two results.
Step 3: Gap 1: run plain insertion sort. Only three pairs are out of order: (3,1), (6,5), and (9,8). Each needs one shift.
Answer: The sorted list is [1, 3, 4, 5, 6, 7, 8, 9]. Shellsort used 3 + 5 + 3 = 11 shifts. Plain insertion sort on the original list would need 23 shifts, one per inversion: 7 + 6 + 1 + 4 + 2 + 2 + 1 = 23. The large gaps moved small values like 1 toward the front in a few long jumps.
Why It Matters
Shellsort needs no extra memory and no recursion, and it takes only a few lines of code. That makes it a practical choice in embedded systems and other memory-limited code. In an algorithms course, it is a standard case study in how the gap sequence controls running time. Shell's original halving gaps give a worst case of order n squared. Knuth's 3h + 1 gaps give order n to the 3/2. The best possible gap sequence is still an open problem.
Common Mistakes
Mistake: Choosing a gap sequence that does not end in 1, or stopping after the larger gaps because the list looks nearly sorted.
Correction: An h-sorted list with h greater than 1 can still be out of order. After the gap-2 pass above, 3 still comes before 1. Only the final gap-1 pass guarantees a sorted result, so every gap sequence must end in 1.
