Data Structures · Sorting

Shell Sort

🔢 The array a[] (same-subsequence members boxed)

key (lifted from this subsequence)the gapsame subsequence as the key (gap positions apart)
result

🧾 Pass record (per gap)

💬 Current step

💻 The algorithm (courseware-style C++)

Yellow = the line being executed. The outer loop drives gap (n/2 → 1); the inner loop is insertion sort — only the stride is gap instead of 1.

📄 Key points

1The gap starts at n/2 and halves each pass
2Elements gap apart form a group; insertion sort inside each group
3A large gap lets values travel far and removes disorder fast
4The final gap = 1 pass: nearly sorted already, so insertion flies
Why large gaps first? With a large gap a value can jump far in one move — big values reach the back and small ones the front quickly, collapsing the disorder; by the time gap = 1 the array is nearly sorted, which is exactly where insertion sort approaches O(n).
Complexity: depends on the gap sequence; the halving sequence is about O(n^1.3), worst case O(n²) (Hibbard’s sequence gives O(n^1.5)); space O(1).
Stability: cross-group moves skip over equal values → not stable.
Its place: the first sorting algorithm to break O(n²), and the model for “sort in groups”, though heap/quick/merge sorts have largely replaced it.
Speed
Shortcuts: Space play/pause · ←→ step · R reset · E result