Shell Sort
Insertion sort on values that are a gap apart, with a shrinking gap. Early passes move keys far, so the last pass finds nearly sorted data.
SolvesSorting
- best
- O(n log n)
- average
- O(n^(3/2))
- worst
- O(n^2)
- space
- O(1)
Insertion sort is slow because a key moves only one slot per shift. Shell sort lets keys
jump. It sorts values that are gap apart first, then shrinks the gap until it is 1.
Already sorted: no key moves in any pass. Each pass only compares, once per key above the gap: O(n log n) with these gap sequences.
gap = 4, key = none
1def shell_sort(a):2 n = len(a)3 gap = n // 24 while gap > 0:5 # insertion sort on every gap-th value6 for i in range(gap, n):7 key = a[i]8 j = i9 while j >= gap and a[j - gap] > key:10 a[j] = a[j - gap]11 j = j - gap12 a[j] = key13 gap = gap // 214 return aStart with gap = n // 2 = 4.
- comparisons
- 0
- shifts
- 0
How it works
For a given gap, the array is gap interleaved lists: indices 0, gap, 2·gap, …, then
1, 1 + gap, …, and so on. A pass runs insertion sort on every one of these lists. After it, the
array is gap-sorted.
- Pick a large gap and gap-sort the array. Keys travel far with few shifts.
- Shrink the gap and gap-sort again. Earlier work is not undone: a gap-sorted array stays gap-sorted after a pass with a smaller gap.
- The last pass has gap 1. It is plain insertion sort, but the array is already nearly sorted.
Shell published the idea in 1959. The running time depends on the gap sequence [1].
Complexity
| Case | Input | Time |
|---|---|---|
| Best | sorted | |
| Average | random | depends on gaps, about |
| Worst | odd positions hold the small values | for halving gaps, for Knuth gaps |
Halving gaps have a bad case: with gaps that are powers of two, large values at even positions and small values at odd positions never meet until gap 1. Knuth gaps (1, 4, 13, 40, …) avoid it: two neighbouring gaps and share no common factor.
Implementations
- Shell gaps: halve the gap each pass. Easy to explain.
- Knuth gaps: , used from the largest below down to 1.
Pitfalls
- The last gap must be 1. Otherwise the array is only gap-sorted.
- The sort is not stable: a long jump can move a key past an equal one.
Related
References
- D. E. Knuth, The Art of Computer Programming, Volume 3: Sorting and Searching, 2nd ed., Addison-Wesley, 1998.
Further reading
- K. Mehlhorn and P. Sanders, Algorithms and Data Structures: The Basic Toolbox, Springer, 2008.