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 starts by comparing elements far apart; the gap halves every round.
gap = n / 2while 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 - gapgap = gap / 2
#Step by step
- 01Start with gap = n/2.
- 02Insertion sort the elements that are gap apart.
- 03Halve the gap.
- 04Repeat until the gap is 1.
- 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
| Best | O(n log n) |
|---|---|
| Average | ≈ O(n^1.3) |
| Worst | O(n²) |
| Extra memory | O(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
Shell sort is an improved version of which algorithm?
- 1Insertion sort
- 2Bubble sort
- 3Merge sort
- 4Quick sort
How does the gap change in shell sort?
- 1It shrinks each round down to 1
- 2It grows each round
- 3It stays fixed
- 4It is random
Is shell sort stable?
- 1No
- 2Yes
Medium
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
What determines shell sort's complexity the most?
- 1The gap sequence
- 2The first element
- 3The programming language
- 4The amount of memory