Now, a 3-sort:
4
1
3
5
2
6
9
12
7
18
17
13
Finally a normal insertion sort will produce the sorted array:
1
2
3
4
5
6
7
9
12
13
17
18
Notice that by the time we do this last insertion sort, most
elements don't have a long way to go before being inserted.
So now the question becomes, do we always do a 5, 3 and 1
sort? The answer is no. In general, we can see that shell sort
will ALWAYS work as long as the last "pass" is a 1-sort.
The important question is, how do we space out the previous
sorts. In particular, we'll call h
1
, h
2
, h
3
, h
t
, an increment
sequence. For shellsort, first we will sort every h
t
values using
insertion sort, then every h
t-1
values and so on...until we at last
sort every h
1
values. (We must have h
1
=1 as previously
mentioned.)
What tends to work well is if each of the values in the
increment sequence are in a geometric series. A good example
would be 1, 2, 4, 8, 16, etc. Thus, if we were sorting 1000 values,
our first sort may be a 256-sort. (Followed by a 128 sort, a 64
sort, etc.) Notice how quickly these initial "passes" will run.
Generally, they will be O(n) time. As time goes on, they will be
a bit slower, but not nearly as slow as the original insertion
sort. In practice, it turns out that a geometric ratio of 2.2
produces the best results. (Roughly this would correspond to
the gap sequence 1, 2, 5, 11, etc.) The actual average case
analysis of this sort is too difficult. (Our textbook states that
experimental results indicate an average running time of
O(n
1.25
).)