/utils

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.

1021324354657687

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 a
1 / 59

Start 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.

  1. Pick a large gap and gap-sort the array. Keys travel far with few shifts.
  2. 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.
  3. 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

CaseInputTime
BestsortedO(nlog⁡n)O(n \log n)
Averagerandomdepends on gaps, about O(n3/2)O(n^{3/2})
Worstodd positions hold the small valuesΘ(n2)\Theta(n^2) for halving gaps, O(n3/2)O(n^{3/2}) 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 hh and 3h+13h + 1 share no common factor.

Implementations

  • Shell gaps: halve the gap each pass. Easy to explain.
  • Knuth gaps: hk+1=3hk+1h_{k+1} = 3h_k + 1, used from the largest below n/3n/3 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

  1. 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.

Full bibliography