Shell Sort

Speeds up insertion sort by comparing far-apart elements first and shrinking the gap.

Worth knowing first

#How does it work?

Shell sort improves insertion sort. Insertion sort can only shift elements one place at a time, so bringing a far-away element home takes long.

Shell sort first compares and swaps elements far apart (for example n/2 apart). Small elements jump towards the front in big steps. The gap shrinks every round until it reaches 1.

The final round is a plain insertion sort, but by then the array is nearly sorted, so it finishes quickly.

#Live animation

$ shell_sort --visualizeStep 1/33

Shell sort starts by comparing elements far apart; the gap halves every round.

Comparisons: 0Swaps: 0ComparingSwappingIn place
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

#Step by step

  1. 01Start with gap = n/2.
  2. 02Insertion sort the elements that are gap apart.
  3. 03Halve the gap.
  4. 04Repeat until the gap is 1.
  5. 05The last round (gap = 1) sorts the array completely.

#Example code

The same algorithm in 8 languages. Every program is compiled, run and checked to print the same output.

def shell_sort(a: list[int]) -> None:
    """Insertion sort on elements `gap` apart, with the gap halving down to 1."""
    gap = len(a) // 2
    while gap > 0:
        for i in range(gap, len(a)):
            key, j = a[i], i
            while j >= gap and a[j - gap] > key:
                a[j] = a[j - gap]
                j -= gap
            a[j] = key
        gap //= 2


numbers = [5, 1, 4, 2, 8, 3]
shell_sort(numbers)
print(*numbers)

#Complexity

BestO(n log n)
Average≈ O(n^1.3)
WorstO(n²)
Extra memoryO(1)
Stable?No
In place?Yes

The complexity depends on the gap sequence. With the simple n/2, n/4, … sequence the worst case is O(n²); better sequences (Knuth, Ciura) bring it to O(n^1.5) and below. An exact average-case analysis is still an open problem.

#When to use it?

Used when you want short code, no extra memory, and something much faster than insertion sort on medium-sized arrays. Common in embedded systems and in some libraries' small-array paths.

#Practice

Log in to answer questions and save your progress.

Easy

1/3

Shell sort is an improved version of which algorithm?

  • 1Insertion sort
  • 2Bubble sort
  • 3Merge sort
  • 4Quick sort

Medium

1/1

For 8 elements, what is the gap sequence starting at n/2?

  • 14, 2, 1
  • 28, 4, 2, 1
  • 33, 2, 1
  • 44, 3, 2, 1

Hard

1/1

What determines shell sort's complexity the most?

  • 1The gap sequence
  • 2The first element
  • 3The programming language
  • 4The amount of memory