Algorithms · Visualized
Shell Sort
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
Shell Sort improves on Insertion Sort by first comparing elements that are far apart (a 'gap'), gradually shrinking that gap down to 1. Time: depends on gap sequence, roughly O(n^1.3) average, O(n²) worst; space: O(1) — sorts in place.
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Shell Sort
SortingShell Sort improves on Insertion Sort by first comparing elements that are far apart (a 'gap'), gradually shrinking that gap down to 1. Sorting distant elements early removes a lot of the 'shifting' work that plain Insertion Sort would otherwise need.
How Shell Sort Works
- Choose a starting gap value (a common choice is half the array length).
- Compare elements that are 'gap' positions apart and swap/insert them into order, just like insertion sort but with a big step size.
- Reduce the gap (commonly by dividing it in half) and repeat the gapped insertion sort.
- Continue shrinking the gap until it becomes 1.
- When gap = 1, this is a normal insertion sort pass, which finishes the job on an array that is now mostly sorted.
Shell Sort Worked Example
Input: [9, 8, 3, 7, 5, 6, 4, 1]
With gap=4: compare index0&4 (9,5)→swap, index1&5 (8,6)→swap, index2&6 (3,4)→ok, index3&7 (7,1)→swap → [5,6,3,1,9,8,4,7]. Gap=2: sort each of the two interleaved subsequences → [3,1,4,6,5,7,9,8] roughly. Gap=1: final plain insertion sort pass cleans up the rest → fully sorted array.
def shell_sort(a):
n = len(a)
gap = n // 2
while gap > 0:
for i in range(gap, n):
key = a[i]
j = i
while j >= gap and a[j - gap] > key:
a[j] = a[j - gap]
j -= gap
a[j] = key
gap //= 2
return aBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Shell Sort Time & Space Complexity
When to Use Shell Sort
- Medium-sized arrays where you want better-than-O(n²) performance without the complexity of merge/quick sort.
- Embedded systems with tight memory limits, since it needs no extra space.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.