Shell Sort
Shell Sort Algorithm
ALGORITHM ShellSort(A[0..n-1])
// Sorts a given array by shell sort
// Input: An array A[0..n-1] of n orderable elements
// Output: Array A[0..n-1] sorted in nondecreasing order
len = size(A);
gap = floor(len/2);
while (gap > 0)
for i = gap to len 1 do
key A[i]
ji
while j >= gap && A[j - gap] > key
A[j] A[j gap];
j j gap
end while
A[j] key
end for
gap floor(gap/2)
end while
Shell sort Example
Sort: 18 32 12 5 38 33 16 2
8 Numbers to be sorted, Shells increment will be floor(n/2)
* floor(8/2) floor(4) = 4
increment 4: 1
18 32 12 5 38 33 16
(visualize colors)
2
Step 1) Only look at 18 and 38 and sort in order ;
18 and 38 stays at its current position because they are in order.
Step 2) Only look at 32 and 33 and sort in order ;
32 and 33 stays at its current position because they are in order.
Step 3) Only look at 12 and 16 and sort in order ;
12 and 16 stays at its current position because they are in order.
Step 4) Only look at 5 and 2 and sort in order ;
2 and 5 need to be switched to be in order.
Shell sort Example (contd.)
Sort: 18 32 12 5 38 33 16 2
Resulting numbers after increment 4 pass:
18 32 12 2
38 33 16 5
* floor(4/2) floor(2) = 2
increment 2:
18
2
32
12
38
33
16
Step 1) Look at 18, 12, 38, 16 and sort them in their appropriate location:
12
38
16
18
33
38
Step 2) Look at 32, 2, 33, 5 and sort them in their appropriate location:
12
16
18
32
38
33
Shell sort Example (contd.)
Sort: 18 32 12 5 38 33 16 2
* floor(2/2) floor(1) = 1
increment 1: 1
12
16
18
32
38
33
12
16
18
32
33
38
The last increment or phase of Shellsort is basically an Insertion
Sort algorithm.