Shell Sort
Shell sort (Shell Sort) is an efficient improved version of insertion sort, proposed by Donald Shell in 1959.
The core idea of shell sort isto divide the original list into multiple subsequences, first perform insertion sort on each subsequence, then gradually shrink the gap between subsequences, and finally perform one standard insertion sort on the whole list. This approach allows elements to move over large distances, thereby eliminating a large number of inversions in the early stages and significantly improving sorting efficiency.
Imagine organizing a deck of shuffled cards. Insertion sort is like picking up cards one at a time and inserting each into the correct position of the sorted pile in your hand. Shell sort, on the other hand, is like first drawing cards every few positions to form a small pile and sorting it, then shrinking the drawing interval and repeating the process. When the interval shrinks to 1, it becomes a standard insertion sort, but by then the whole sequence is already nearly sorted, so the final insertion sort is very fast.
How It Works
The key to shell sort lies in a concept called gap sequence . The gap sequence determines the interval for dividing subsequences each time. The algorithm performs multiple rounds of sorting on the list according to a gradually decreasing gap sequence.
Algorithm steps
- Choose the gap sequence: determine a sequence of integers from large to small, where the last gap must be 1. The most commonly used initial gap is half the array length, then halve it each time.
- Group by gap: for the current gap
gap, divide the whole list intogapsubsequences. Each subsequence is made up of all elements with an interval ofgap. - Perform insertion sort on the subsequences: perform insertion sort on each subsequence separately.
- Decrease the gap: obtain a new, smaller gap, and repeat steps 2 and 3.
- Final sort: when the gap decreases to 1, perform one standard insertion sort on the whole list; at this point the list is already nearly sorted, so the sort completes quickly.
Applicability Notes
The time complexity of shell sort is O(n^(1.3-2)), and its space complexity is constant order O(1). Shell sort is not as fast as the quick sort algorithm with time complexity O(n(logn)), so it performs well on medium-sized data, but is not the optimal choice for sorting very large datasets; in any case, it is much faster than algorithms of general O(n^2 ) complexity.
Process Diagram
Shell sort improves insertion sort for the purpose of speeding it up; it swaps non-adjacent elements to sort local parts of the array, and finally uses insertion sort to sort the locally ordered array.
Here we choose the gap = length/2 and shrink the gap by gap = gap/2, using the sequence {n/2,(n/2)/2...1} .
As shown in the figure:
(1) Initial gap, first pass: gap = length/2 = 4

(2) Second pass: the gap shrinks to 2

(3) Third pass: the gap shrinks to 1, giving the final sorted result

Java Example Code
Source code package download:Download
The innermost loop is actually insertion sort:
ShellSort.java file code:
public
class
ShellSort
{
// Core code---start
public
static
void
sort
(
Comparable
[
]
arr
)
{
int
j
;
for
(
int
gap
=
arr.
length
/
2
;
gap
0
;
gap
/=
2
)
{
for
(
int
i
=
gap
;
i
<
arr.
length
;
i
++
)
{
Comparable
tmp
=
arr
[
i
]
;
for
(
j
=
i
;
j
=
gap
&&
tmp.
compareTo
(
arr
[
j
gap
]
)
<
0
;
j
-=
gap
)
{
arr
[
j
]
=
arr
[
j
gap
]
;
}
arr
[
j
]
=
tmp
;
}
}
}
// Core code---end
public
static
void
main
(
String
[
]
args
)
{
int
N
=
2000
;
Integer
[
]
arr
=
SortTestHelper.
generateRandomArray
(
N,
0
,
10
)
;
ShellSort.
sort
(
arr
)
;
for
(
int
i
=
0
;
i
<
arr.
length
;
i
++
)
{
System
.
out
.
(
arr
[
i
]
)
;
System
.
out
.
(
' '
)
;
}
}
}
Python algorithm implementation
We will use Python to implement shell sort, adopting the most common gap setting (the original Shell sequence):gap = n // 2, and continuously perform gap integer division by 2 on it until gap it is 1.
Example
def
shell_sort
(
arr
)
:
"""
Sort a list in place in ascending order using the shell sort algorithm.
Parameters:
arr (list): the list to be sorted.
Returns:
list: the sorted list (modified in place and also returned).
"""
n
=
len
(
arr
)
Initialize the gap to half the array length
gap
=
n //
2
Loop until the gap shrinks to 0
while
gap
0
:
Starting from gap, perform 'insertion sort' on each element
Note: here i goes from gap to n-1, traversing all elements
for
i
in
range
(
gap
,
n
)
:
Save arr[i] to the temporary variable temp
temp
=
arr
[
i
]
j
=
i
Perform insertion sort on the subsequence under the current gap
If an earlier element in the same subsequence is greater than temp, move it backward
while
j
=
gap
and
arr
[
j - gap
]
temp:
arr
[
j
]
=
arr
[
j - gap
]
j -
=
gap
Insert temp into its correct position
arr
[
j
]
=
temp
Decrease the gap, e.g., halve the gap
gap //
=
2
return
arr
Test code
if
name
==
"main"
:
Test data 1: randomly shuffled
test_array
=
[
8
,
3
,
5
,
1
,
4
,
2
,
7
,
6
]
(
"Before sorting:"
,
test_array
)
sorted_array
=
shell_sort
(
test_array.
copy
(
)
)
Use copy to avoid modifying the original array
(
"After sorting:"
,
sorted_array
)
Test data 2: containing duplicate elements
test_array2
=
[
5
,
2
,
9
,
5
,
2
,
3
,
5
]
(
"\nBefore sorting:"
,
test_array2
)
(
"After sorting:"
,
shell_sort
(
test_array2.
copy
(
)
)
)
Test data 3: reverse-ordered array
test_array3
=
[
10
,
9
,
8
,
7
,
6
,
5
,
4
,
3
,
2
,
1
]
(
"\nBefore sorting:"
,
test_array3
)
(
"After sorting:"
,
shell_sort
(
test_array3.
copy
(
)
)
)
Code analysis:
def shell_sort(arr):Define the shell sort function.n = len(arr)Get the array length.gap = n // 2Initialize the gap. This is the most classic starting point of the gap sequence for shell sort.while gap > 0:The outer loop controls the gap gradually decreasing until it is 0 (actually after finishing at 1,gap //= 2it becomes 0 and exits).for i in range(gap, n):The inner loop. Starting from indexgapand traversing.ipoints to the element currently to be inserted. Note that this loop cleverly handles all subsequences spaced bygapat the same time.temp = arr[i]andj = i: save the value of the current element, and usejto record the position where it should be inserted in the current subsequence.while j >= gap and arr[j - gap] > temp:This is the core of insertion sort. Within the same subsequence (accessingj - gapthe previous element by index), if the previous element istempgreater than it, move the previous element backward bygappositions.arr[j] = temp: insert the savedtempvalue into its correct position.gap //= 2: after one round of sorting, halve the gap and proceed to the next, finer round of sorting.return arr: return the sorted array.
Choice of gap sequence
The choice of gap sequence directly affects the performance of shell sort. Above we used the original Shell sequence (n/2, n/4, ..., 1), but it is not optimal. Several common gap sequences are introduced below:
| Sequence name | Generation formula | Features and complexity |
|---|---|---|
| Original Shell sequence | $gap = \lfloor \frac{n}{2} \rfloor, gap = \lfloor \frac{gap}{2} \rfloor...$ | Simple to implement, with worst-case time complexity $O(n^2)$. |
| Hibbard sequence | $1, 3, 7, 15, ..., 2^k - 1$ | Worst-case time complexity can be improved to $O(n^{3/2})$. |
| Knuth sequence | $1, 4, 13, 40, ..., (3^k - 1) / 2$ (less than n) | Average time complexity is about $O(n^{1.25})$, commonly used in practice. |
| Sedgewick sequence | $1, 5, 19, 41, 109, ...$ (mixing $9 \times 4^k - 9 \times 2^k + 1$ and $4^k - 3 \times 2^k + 1$) | It is one of the best known sequences, with worst-case complexity reaching $O(n^{4/3})$. |
Implementation example using the Knuth sequence
Example
def
shell_sort_knuth
(
arr
)
:
n
=
len
(
arr
)
Generate the Knuth gap sequence: 1, 4, 13, 40, 121, ...
gap
=
1
while
gap
<
n //
3
:
gap
=
3
- gap +
1
Generate the largest initial gap
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 //
=
3
Knuth suggests dividing by 3 each time
return
arr
Test the Knuth sequence version
test_array
=
[
33
,
12
,
56
,
78
,
2
,
45
,
67
,
89
,
1
,
23
]
(
"Before Knuth sequence sort:"
,
test_array
)
(
"After Knuth sequence sort:"
,
shell_sort_knuth
(
test_array.
copy
(
)
)
)
Algorithm characteristics and complexity analysis
Time Complexity
The time complexity analysis of shell sort is very complex because it depends on the chosen gap sequence.
- Worst Case: when using the original Shell sequence, the worst-case time complexity is $O(n^2)$.
- Average Case: for better gap sequences (such as Knuth, Sedgewick), the average time complexity is between $O(n^{1.25})$ and $O(n^{1.5})$.
- Best Case: when the array is already sorted, the complexity can approach $O(n \log n)$.
Space complexity
- Shell sort is a in-place sort algorithm requires only constant-level extra space (such as
temp,gap,i,jetc.), so the space complexity is $O(1)$.
Stability
- Shell sort is a Unstable sorting algorithm. Because when sorting by gap grouping, the same elements may be assigned to different subsequences and their relative order changed by moves.
A simple comparison with other sorting algorithms
| Feature | Shell Sort | Insertion Sort | Merge Sort | Quick Sort |
|---|---|---|---|---|
| Average time complexity | $O(n^{1.25})$ ~ $O(n^{1.5})$ | $O(n^2)$ | $O(n \log n)$ | $O(n \log n)$ |
| Space complexity | $O(1)$ | $O(1)$ | $O(n)$ | $O(\log n)$ |
| Stability | Unstable | Stable | Stable | Unstable |
| Advantages | Performs well on medium-sized data, sorts in place | Simple, efficient for small or nearly sorted data | Stable, with good time complexity | Fastest in the average case |
| Disadvantages | Complexity is hard to analyze; choice of gap sequence has a big impact | Inefficient for large datasets | Requires extra space | Worst case degrades to $O(n^2)$ |