希尔排序( Shell Sort)

时间:2023-03-08 17:25:02

原文地址:http://www.stoimen.com/blog/,在此感谢作者!

Insertion sort is a great algorithm, because it’s very intuitive and it is easy to implement, but the problem
is that it makes many exchanges for each “light” element in order to put it on the right place. Thus
“light” elements at the end of the list may slow down the performance of insertion sort a lot. That is why
in 1959 Donald Shell proposed an algorithm that tries to overcome this problem by comparing items of
the list that lie far apart.

希尔排序( Shell Sort)

How to choose gap size
Not a cool thing about Shell sort is that we’ve to choose “the perfect” gap sequence for our list. However
this is not an easy task, because it depends a lot of the input data. The good news is that there are some
gap sequences proved to be working well in the general cases.

Shell Sequence
Donald Shell proposes a sequence that follows the formula FLOOR(N/2 ), then for N = 1000, we get the
following sequence: [500, 250, 125, 62, 31, 15, 7, 3, 1]

Pratt Sequence
Pratt proposes another sequence that’s growing with a slower pace than the Shell’s sequence. He
proposes successive numbers of the form (2^q)* (3^q) or [1, 2, 3, 4, 6, 8, 9, 12, …].

Knuth Sequence
Knuth in other hand proposes his own sequence following the formula (3^k – 1) / 2 or [1, 4, 14, 40, 121, …]

Complexity
Yet again we can’t determine the exact complexity of this algorithm, because it depends on the gap
sequence. However we may say what is the complexity of Shell sort with the sequences of Knuth, Pratt
and Donald Shell. For the Shell’s sequence the complexity is O(n*n ), while for the Pratt’s sequence it is
O(n*log (n)). The best approach is the Knuth sequence where the complexity is O(n^(3/2) ), as you can see
on the diagram bellow.

希尔排序( Shell Sort)

Application
Well, as insertion sort and bubble sort, Shell sort is not very effective compared to quicksort or merge
sort. The good thing is that it is quite easy to implement (not easier than insertion sort), but in general it
should be avoided for large data sets. Perhaps the main advantage of Shell sort is that the list can be
sorted for a gap greater than 1 and thus making less exchanges than insertion sort.