Insert sorting before analyzing the hill sorting:
1 void InsertSort(int A[],int N)
2 {
3 int j,p,temp;
4 for(p=1;p<N;p++)
5 {
6 temp=A[p];
7 for(j=p;j>0&&A[j-1]>temp;j--)
8 {
9 A[j]=A[j-1];
10 }
11 A[j]=temp;
12 }
13 }
The row 4th shows that the inserted element starts from the first one (with the first 0th ). Find the position of the inserted element through the loop between rows 7th and 10th, and then put the element to be inserted through the statement of row 11th.
Note that each insert operation starts from the position of the element to be inserted, rather than starting from the end of the array.
The following code is the hill Sorting code:
1 void Shell_Sort(int a[], int n)
2 {
3 int h,i,j,temp;
4 for (h=n/2; h>0; h=h/2)
5 {
6 for (i=h; i<n; i++)
7 {
8 temp = a[i];
9 for (j=i-h; j>=0 && temp < a[j]; j-=h)
10 {
11 a[j+h] = a[j];
12 }
13 a[j+h] = temp;
14 }
15 }
16
17 }
The idea of hill sorting is the same as that of insert sorting. It is to insert data from the first (0th in front) to the front. However, Hill sorting sorts the incremental data, and the incremental data is a descending incremental sequence.
In the hill sorting, the code from 9th rows to 12th rows act the same as the insert sorting, and the data separated by H is inserted and sorted. H satisfies the shell sequence: n' = n/2. In the preceding example, 1, 2, 5 .......
The sorting process can be expressed as follows:
H = 5:
10 | 9 | 8 | 7 | 6
5 | 4 | 3 | 2 | 1
H = 2:
10 | 9
8 | 7
6 | 5
4 | 3
2 | 1
H = 1:
10
9
8
7
6
5
4
3
2
1
Data in each column is sorted only.
When H gets a value, 6th lines of code scan each column, 8th ~ 13 lines of code to sort the columns.