Shell Sort, explained step by step

Shell Sort generalises Insertion Sort by first sorting elements that are far apart, then progressively reducing the gap. By the time the gap is 1, the array is nearly sorted and the final insertion sort is fast.

Intuition: Roughly arrange a bookshelf by sections first, then fine-tune book by book.

How it works

  1. Choose a gap sequence (here n/2, n/4, …, 1).
  2. For each gap, run insertion sort on every sub-list of elements gap apart.
  3. Halve the gap and repeat.
  4. The last pass (gap 1) is an insertion sort on an almost-sorted array.

Complexity

  • Best: O(n log n)
  • Average: Gap-dependent
  • Worst: O(n²)
  • Space: O(1)
  • Stable: no

When to use it

Medium-sized arrays and embedded systems where recursion or extra memory is undesirable.

Interview questions

  • How does the gap sequence affect Shell Sort’s complexity?
  • Why is Shell Sort faster than plain Insertion Sort?

Compare Shell Sort

Open Shell Sort in the visualiser