Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Shell Sort

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

  1. 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.
  2. Group by gap: for the current gap gap, divide the whole list into gap subsequences. Each subsequence is made up of all elements with an interval of gap .
  3. Perform insertion sort on the subsequences: perform insertion sort on each subsequence separately.
  4. Decrease the gap: obtain a new, smaller gap, and repeat steps 2 and 3.
  5. 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

.

print

(

arr

[

i

]

)

;

           

System

.

out

.

print

(

' '

)

;

       

}

   

}

}


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

]

   

print

(

"Before sorting:"

,

test_array

)

    sorted_array

=

shell_sort

(

test_array.

copy

(

)

)

Use copy to avoid modifying the original array

   

print

(

"After sorting:"

,

sorted_array

)

   

   

Test data 2: containing duplicate elements

    test_array2

=

[

5

,

2

,

9

,

5

,

2

,

3

,

5

]

   

print

(

"\nBefore sorting:"

,

test_array2

)

   

print

(

"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

]

   

print

(

"\nBefore sorting:"

,

test_array3

)

   

print

(

"After sorting:"

,

shell_sort

(

test_array3.

copy

(

)

)

)

Code analysis:

  1. def shell_sort(arr): Define the shell sort function.
  2. n = len(arr) Get the array length.
  3. gap = n // 2 Initialize the gap. This is the most classic starting point of the gap sequence for shell sort.
  4. while gap > 0: The outer loop controls the gap gradually decreasing until it is 0 (actually after finishing at 1,gap //= 2 it becomes 0 and exits).
  5. for i in range(gap, n): The inner loop. Starting from index gap and traversing.i points to the element currently to be inserted. Note that this loop cleverly handles all subsequences spaced by gap at the same time.
  6. temp = arr[i] and j = i: save the value of the current element, and use j to record the position where it should be inserted in the current subsequence.
  7. while j >= gap and arr[j - gap] > temp: This is the core of insertion sort. Within the same subsequence (accessing j - gap the previous element by index), if the previous element is temp greater than it, move the previous element backward by gap positions.
  8. arr[j] = temp: insert the saved temp value into its correct position.
  9. gap //= 2: after one round of sorting, halve the gap and proceed to the next, finer round of sorting.
  10. 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

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

]

print

(

"Before Knuth sequence sort:"

,

test_array

)

print

(

"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.

Space complexity

Stability

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)$

More Code Examples