AlgoLab

O(n^1.3)·O(1) space·not stable
645559896316373459948511843281951114277

Starting shell sort on an array of 20 items.

Starting shell sort on an array of 20 items.
  1. 1set the gap to half the array length
  2. 2for each position from the gap to the last, remember its value as the one being inserted
  3. 3compare the remembered value with the value one gap-width to its left
  4. 4if the value to the left is greater, shift it one gap-width to the right
  5. 5place the remembered value into the gap the shifting left behind
  6. 6once every position has been processed, halve the gap and repeat; when it reaches zero, the array is fully sorted
Comparisons
0
Writes
0
Accesses
0

Complexity

BestO(n log n)
AverageO(n^1.3)
WorstO(n²)
Extra spaceO(1)
StableNo
n² at n=20 predicts 400; this run took 0.

Shell sort

Shell sort is insertion sort generalised to compare and shift values that are a fixed gap apart rather than adjacent. It starts with a large gap — half the array length, here — and after a full pass at each gap, halves the gap and repeats, finishing with a gap of one, which is ordinary insertion sort on an array that earlier passes have already roughly ordered.

When it is the right choice

Shell sort is worth reaching for when insertion sort is nearly fast enough but n is a bit too large for its O(n²) worst case, and an in-place sort with no recursion is preferred over quicksort or merge sort. It is rarely the fastest option available, but it is simple to implement, and its performance depends heavily on the choice of gap sequence — the halving sequence used here is the simplest, not the best known.

How it works

Worth noticing

Cost

Best
O(n log n)
Average
O(n^1.3)
Worst
O(n²)
Extra space
O(1)
Stable
No

Worth comparing

All algorithms