shellsort

advertisement
Shell Sort - an improvement on the Insertion Sort
Review insertion sort:
when most efficient?
when almost in order. (can be close to O(n))
when least efficient?
when values must be moved a long distance.
(ex. small value near bottom requires shifting
everything down)
(if that is true for many items: n shifts must be
made for each n items resulting in O(n2)
Shell sort is 2nd fastest general sort and
is good for medium size arrays (up to a few thousand)
The Shell sort is not much different in the worst case
than in the average case.
Knuth’s interval sequence is one way of generating the
largest ‘gap’ to begin sorting items that are that far the size of the interval - apart to compare and sort.
This method uses the recursive definition h = 3*h+1
until h > array length (base case) to find the starting
gap.
After all elements are sorted for some h, all element h
units apart are in order w.r.t. themselves.
1. After an array has been “4-sorted”
all items 4 units apart are in order w.r.t.themselves.
2. Also, no item is more than 2 cells from its proper
place.
3. A 1-unit sort - the insertion sort - is then applied.
Why is the Shell Sort faster than just the insertion?
When h is large, the number of items moved per pass
is small and items move long distances.
As h gets smaller, the no. of items per pass gets larger,
but the items are already closer together.
Complexity of Shell Sort: O(n*(log n)2 )
Download