2007-04-22

Shell Sort

Shell sort is a sorting algorithm that, with its original implementation, requires O(n2) comparisons and exchanges in the worst case. A minor change given in V. Pratt's book produces an implementation with worst case performance of O(nlog2 n). This is better than the O(n2) comparisons required by naive algorithms but worse than the optimal O(n log n) (see comparison sort). Although it is easy to develop an intuitive sense of how this algorithm works, it is very difficult to analyze its execution time.

Shell sort is a generalization of insertion sort, with two observations in mind:

1. Insertion sort is efficient if the input is "almost sorted".
2. Insertion sort is inefficient, on average, because it moves values just one position at a time.

Shell sort improves insertion sort by comparing elements separated by a gap of several positions. This lets an element take "bigger steps" toward its expected position. Multiple passes over the data are taken with smaller and smaller gap sizes. The last step of Shell sort is a plain insertion sort, but by then, the array of data is guaranteed to be almost sorted.

Consider a small value that is initially stored in the wrong end of the array. Using an O(n2) sort such as bubble sort or insertion sort, it will take roughly n comparisons and exchanges to move this value all the way to the other end of the array. Shell sort first moves values using giant step sizes, so a small value will move a long way towards its final position, with just a few comparisons and exchanges.


Read more...

No comments: