Shell Sort visualization

Insertion sort over shrinking gaps, so values travel long distances early.

Elements gap apart are insertion-sorted first. Big gaps move far-away values quickly; the final gap of 1 is an ordinary insertion sort on an almost-sorted array.

Complexity depends on the gap sequence. With halving gaps it is O(n²) worst case, but much faster in practice.

Complexity

Time: best O(n log n), average ≈O(n^1.25), worst O(n²). Space: O(1). Difficulty: Intermediate.

Pseudocode

procedure shellSort(A):
  gap ← n / 2
  while gap > 0:
    for i ← gap to n−1:
      j ← i
      while j ≥ gap and A[j−gap] > A[j]:
        swap(A[j], A[j−gap]); j ← j − gap
    gap ← gap / 2

More sorting algorithms