Shell Sort
Last updated
Was this helpful?
Last updated
Was this helpful?
Shellsort is a more refined version of insertion sort. This algorithm will change our array from completely random unsorted data to partially sorted data so that insertion sort may work faster.
This algorithm works by using increments, the increments can be found . For this Article I will make us of the increment $N/2^k$.
What we do with the increments is we keep applying it till we get 1 as an increment, once we have 1 we know we are using the last insertion sort.
Let's take this array as an example:
we now know that our N = 16, and the first increment therefor becomes: 8. We now split our array in 2
Once we did that, we sort the columns:
And we go to the next increment (here that is 8 / 2 = 4) and sort.
Next increment = 2
Next increment is our last increment = 1
Which sorted the complete array.
For the implementation check paragraph §3.4
.
Advantages
Requires $O(1)$ extra space
Performance of $O(n^{7/6})$ for the best currently known sequence
$O(n * lg(n))$ when almost sorted.
Disadvantages
Not stable
Worst Case
Average Case
Best Case
$O(n^{7/6})$
-
$O(n * log^2(n))$
The performance of ShellSort depends on the used gap sequence, because the best gap sequence is not yet known. We are unable to say which the best case is. Currently one of the best gap sequences is the one of Tokuda (1992): $k_i = \frac{9^5 - 4^k}{5 * 4^{k - 1}}$ with a performance of $O(n^{7/6})$.
When we watch §1.1
we know how the algorithm works, so we write down what we will need:
Get initial increment
Use insertion sort with rebased indexes
This means our pseudocode is the same as the one for Insertion Sort, only with the difference of the gap index.
100
1.000
10.000
100.000
1.000.000
Random Elements
1.2e-05
0.000191
0.002876
0.041843
0.565456
Ascending Elements
4e-06
6e-05
0.000892
0.011036
0.12966
Descending Elements
7e-06
9.1e-05
0.001226
0.015739
0.178499
When we have to use a fast algorithm that is easy to implement, and the performance that we require is not ultimate. Then Shell Sort is the facto standard to use.