1. Algorithm idea
The entire sequence of elements to be sorted into a number of sub-sequences (consisting of an element separated by an "increment") is directly inserted into the sort, and then reduced incrementally and then sorted, and then the entire sequence of elements in order (the increment is small enough), then the whole element of a direct insertion sort. Because the direct insert sort is very efficient when the elements are basically ordered (close to the best case), the hill sort is more efficient in time than the first two methods.
The Hill (Shell) sort is also known as narrowing the incremental sort, which is an insertion sort. It is a powerful version of the direct insertion sorting algorithm.
The basic idea of Hill sort is
The records are grouped by step gap, and the direct insertion sorting method is used to sort each group of records.
As the stride size decreases, the grouped groups contain more and more records, and when the step value decreases to 1 o'clock, the entire data becomes a group that forms an ordered set of records, and the sort is completed.
In the picture above:
Initially, there is an unordered sequence of size 10.
In the first order, we might as well set gap1 = N/2 = 5, which is a group of elements separated by 5, which can be divided into 5 groups.
Next, sort each group by the method of direct insert sorting.
In the second order, we narrowed the last gap by half, i.e. GAP2 = GAP1/2 = 2 (Take an integer). This makes up a group of 2 elements per distance and can be divided into 2 groups.
Each group is sorted by the method of direct insert sorting.
In the third order, the gap is halved again, i.e. gap3 = GAP2/2 = 1. This makes a group of elements that are 1 apart, that is, only one group.
Each group is sorted by the method of direct insert sorting. At this point, the sort has ended.
It is important to note that there are two elements of equal value 5 and 5 in the figure. We can clearly see that during the sorting process, two element positions are exchanged.
So, the hill sort is an unstable algorithm.
2. Code implementation (strictly defined)
voidShellsort1 (intA[],intN) {intI, J, Gap; for(GAP = n/2; Gap >0; Gap/=2)//Step for(i =0; I < gap; i++)//Direct Insert Sort{ for(j = i + Gap; j < n; j + = Gap)if(A[j] < A[J-GAP]) {inttemp = A[j];intK = J-gap; while(k >=0&& A[k] > Temp) {a[k + gap] = a[k]; K-= gap; } A[k + gap] = temp; } }}
3, improve the code
voidShellsort2 (intA[],intN) {intJ, Gap; for(GAP = n/2; Gap >0; Gap/=2) for(j = Gap; J < N; j + +)//Starting with the gap element of the array if(A[j] < A[J-GAP])//Each element is directly inserted into the sort with data within its own group{inttemp = A[j];intK = J-gap; while(k >=0&& A[k] > Temp) {a[k + gap] = a[k]; K-= gap; } A[k + gap] = temp; }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Algorithm learning sequencing Algorithm (four) (Hill sort)