COMPARISON SORTS
Shell Sort, visualised
Shell sort runs insertion sort on elements a fixed distance (gap) apart, shrinks the gap, and finishes with an ordinary insertion sort.
Run Shell Sort in the visualizer →
Opens the Sorting Cinema visualizer with 16 elements in English.
How it works
- Start with a gap of half the array length, rounded down (this app's implementation).
- Compare elements one gap apart; if the left one is larger, swap and keep stepping back by the gap.
- After a full pass, halve the gap (rounded down).
- When the gap-1 insertion sort finishes, the array is sorted.
Complexity and stability
- Best
- O(n log n)
- Average
- — (no claim on this page)
- Worst
- O(n²)
- Extra space
- O(1)
- Stability
- Usually unstable
The complexity depends on the gap sequence. With this app's sequence (n/2, halving each time) the worst case is O(n²), and on sorted input each gap needs only one round of comparisons, giving O(n log n). This page makes no claim about the average case.
Source of facts: Complexity is derived from the steps of this app's implementation (src/SortingCinema.jsx).
Trace on a small array
The first operations on the input [5, 2, 4, 1, 3], following the same steps as the app.
| # | Operation | Array after |
|---|---|---|
| 1 | Compare [0]=5 and [2]=4 | [5, 2, 4, 1, 3] |
| 2 | Swap [0]=5 and [2]=4 | [4, 2, 5, 1, 3] |
| 3 | Compare [1]=2 and [3]=1 | [4, 2, 5, 1, 3] |
| 4 | Swap [1]=2 and [3]=1 | [4, 1, 5, 2, 3] |
| 5 | Compare [2]=5 and [4]=3 | [4, 1, 5, 2, 3] |
| 6 | Swap [2]=5 and [4]=3 | [4, 1, 3, 2, 5] |
| 7 | Compare [0]=4 and [2]=3 | [4, 1, 3, 2, 5] |
| 8 | Swap [0]=4 and [2]=3 | [3, 1, 4, 2, 5] |
…and so on. In this trace, 17 compare / swap / write operations in total produce [1, 2, 3, 4, 5].
Suitable inputs and caveats
- Moving distant elements first means items travel shorter distances than in plain insertion sort, even on reversed input.
- Performance depends on the gap sequence; this app uses simple halving.
- It swaps distant elements, so it is usually unstable.
FAQ
How does shell sort differ from insertion sort?
Shell sort first orders elements that are far apart, then narrows the gap and finishes with a gap-1 insertion sort. The early long moves reduce the work of the final pass.
Which gap sequence does this app use?
It starts at half the array length and halves (rounding down) each pass. Other gap sequences have different complexities.