Shell Sort
Sort cards far apart first, then bring the gap down to one.
shell sort, gaps, insertion sort, sortingMove cards across bigger gaps
Insertion sort moves a card through neighbouring positions. If a small card starts near the far end, it may need many moves. Shell sort first insertion-sorts positions separated by a larger gap, then repeats with smaller gaps, finishing with gap one.
Why use it and where it helps
The early passes can move items long distances and leave less work for the last pass. Shell sort is a useful bridge between insertion sort and more complex sorting methods. Its speed depends on the gaps and input; it is not always faster than another algorithm.
Follow an example
For [5, 1, 4, 2], use gap 2, then gap 1:
| Pass | Groups or action | Result |
|---|---|---|
| gap 2 | Sort positions 0 and 2; then 1 and 3 | [4, 1, 5, 2] |
| gap 1 | Insertion-sort the whole row | [1, 2, 4, 5] |
With gap 2, positions 0 and 2 form one group; 1 and 3 form the other.
See the reasoning
Follow the example one step at a time
Sort [5, 1, 4, 2] using gaps 2 and 1. This is a prepared teaching demonstration, not live code execution.
Start
[5, 1, 4, 2] gap: 2
With gap 2, positions 0 and 2 form a group; positions 1 and 3 form another.
Python illustration
def shell_sort(numbers):
items = numbers[:]
gap = len(items) // 2
while gap > 0:
for i in range(gap, len(items)):
value = items[i]
j = i
while j >= gap and items[j - gap] > value:
items[j] = items[j - gap]
j -= gap
items[j] = value
gap //= 2
return items
print(shell_sort([5, 1, 4, 2]))
print(shell_sort([]))
Prepared output — not live execution:
[1, 2, 4, 5]
[]
The function copies its input. Its gaps are obtained by repeatedly halving the initial length; other gap sequences are possible. The final positive gap is one whenever the input has at least two items.
Time, space, and common mistakes
The final gap-one pass is a correct insertion sort even if earlier passes did little useful work. This halving-gap version can take O(n²) time in the worst case; do not assume O(n log n). The copy uses O(n) space; the sorting pass itself needs O(1) extra space. Shell sort is generally not stable because gapped moves can carry equal items past one another.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
