Shell sort with Shell gaps uses the original gap sequence proposed for Shell sort. The sequence starts with roughly half the array length and repeatedly halves the gap until it reaches 1.
This version is simple and easy to implement, but its worst-case behavior remains quadratic.
Problem
Given a sequence of length , reorder it such that
Gap Sequence
For an array of length , the Shell gap sequence is:
For example, if , the gaps are:
Algorithm
For each gap, perform insertion sort over subsequences whose elements are separated by that gap.
shell_sort_shell_gaps(A):
n = length(A)
gap = n // 2
while gap > 0:
for i from gap to n - 1:
key = A[i]
j = i
while j >= gap and A[j - gap] > key:
A[j] = A[j - gap]
j = j - gap
A[j] = key
gap = gap // 2Example
Let
For , the gaps are:
Gap 4 pass:
- compare and insert among index groups , , ,
After this pass:
Gap 2 pass partially orders even and odd index groups:
Gap 1 pass finishes with insertion sort:
Correctness
Each gap pass sorts every subsequence formed by taking elements at distance . After the final gap , the whole array is one subsequence, so the final pass is ordinary insertion sort over the entire array. Therefore the output is sorted.
Complexity
| case | time |
|---|---|
| best | |
| worst | |
| average | depends on input |
Space complexity:
Properties
- in-place
- not stable
- simple gap sequence
- weaker than many later Shell sort gap sequences
When to Use
Use Shell gaps when implementation simplicity matters more than precise performance. For production sorting, prefer better gap sequences such as Hibbard, Sedgewick, Tokuda, or Ciura.
Implementation
def shell_sort_shell_gaps(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 afunc ShellSortShellGaps[T constraints.Ordered](a []T) {
n := len(a)
for gap := n / 2; gap > 0; gap /= 2 {
for i := gap; i < n; i++ {
key := a[i]
j := i
for j >= gap && a[j-gap] > key {
a[j] = a[j-gap]
j -= gap
}
a[j] = key
}
}
}