Shell Sort in Data Structure — Algorithm, Visualization and Complexity
Shell Sort is an optimization of Insertion Sort that allows the exchange of elements that are far apart. It works by first sorting elements that are a certain 'gap' distance apart, then progressively reducing the gap until it becomes 1 (a final regular insertion sort pass).
How It Works (Visualization)
For an array of size 8 with an initial gap of 4, elements at positions (0,4), (1,5), (2,6), (3,7) are compared and sorted first. The gap is then reduced (commonly halved, e.g., to 2), and the process repeats with smaller sub-groups, until the gap becomes 1, performing a final full insertion sort pass on the now mostly-sorted array.
def shell_sort(arr):
n = len(arr)
gap = n // 2
while gap > 0:
for i in range(gap, n):
temp = arr[i]
j = i
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap
arr[j] = temp
gap //= 2
return arr
Complexity
| Gap Sequence | Worst Case Time |
|---|---|
| n/2, n/4, ..., 1 (Shell's original) | O(n²) |
| Knuth's sequence (3k+1) | O(n^1.5) |
| Hibbard's sequence | O(n^1.5) |
Advantages
- Significantly faster than plain Insertion Sort or Bubble Sort for medium-sized arrays.
- In-place — requires only O(1) extra space.
- Simple to implement compared to Merge Sort or Quick Sort.
Applications
- Sorting medium-sized datasets where simplicity and low memory use matter.
- Embedded systems with limited memory.
- Used historically in the uClibc library's qsort implementation for small arrays.
Full Dry Run on [35, 33, 42, 10, 14, 19, 27, 44]
Tracing a real array shows why Shell Sort beats plain insertion sort: big jumps early on move small values toward the front quickly, so the final pass has almost nothing left to do.
Gap = 4
Compare elements four places apart: (35, 14) swap, (33, 19) swap, (42, 27) swap, (10, 44) stay. The array becomes [14, 19, 27, 10, 35, 33, 42, 44].
Gap = 2
Now there are two interleaved groups. Even positions hold 14, 27, 35, 42, already in order. Odd positions hold 19, 10, 33, 44; sorting them gives 10, 19, 33, 44. The array becomes [14, 10, 27, 19, 35, 33, 42, 44].
Gap = 1
This is a normal insertion sort, but each element is at most one step from home. Only three small shifts are needed, producing [10, 14, 19, 27, 33, 35, 42, 44]. Running insertion sort on the original array would have required many more shifts, because 10 had to travel from index 3 to index 0 one position at a time.
Using a Better Gap Sequence
Halving the gap is easy to remember but not the best choice. Knuth's sequence (1, 4, 13, 40, 121, ...) usually performs better. You build it upward first, then walk it back down:
def shell_sort_knuth(arr):
n = len(arr)
gap = 1
while gap < n // 3:
gap = 3 * gap + 1 # 1, 4, 13, 40, ...
while gap >= 1:
for i in range(gap, n):
temp = arr[i]
j = i
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap
arr[j] = temp
gap //= 3
return arr
print(shell_sort_knuth([35, 33, 42, 10, 14, 19, 27, 44]))
Other well-known sequences include Sedgewick's and Ciura's. Ciura's sequence (1, 4, 10, 23, 57, 132, 301, 701) was found by experiment and is often quoted as one of the best practical choices. Whatever sequence you use, it must end with a gap of 1, or the array may not be fully sorted.
Shell Sort Compared With Other Sorts
| Algorithm | Extra space | Stable | Typical use |
|---|---|---|---|
| Insertion Sort | O(1) | Yes | Tiny or nearly sorted arrays |
| Shell Sort | O(1) | No | Medium arrays with tight memory |
| Merge Sort | O(n) | Yes | Large data, stable ordering needed |
| Quick Sort | O(log n) stack | No | Fast general-purpose sorting |
Shell Sort is not stable because long-distance moves can carry an element past an equal one. If you sort records by marks and need students with equal marks to keep their original order, choose a stable algorithm instead.
Common Errors When Coding It
- Writing
j > gapinstead ofj >= gap, which skips the first element of each group. - Swapping on every comparison instead of shifting and placing
temponce; it works but does extra writes. - Using a sequence that never reaches 1, leaving the array partly unsorted.
- Quoting a single complexity for Shell Sort. Its running time depends on the gap sequence, so always state which sequence you mean.
Quick recap: pick a gap sequence ending in 1, run gapped insertion sort for each gap from large to small, and remember that the method is in-place but unstable.