First pasting the code
. 1 #include <stdio.h> 2 #define N 12 is . 3 // longitudinal length of the return statistic array index of the last element . 4 int length ( int A [N]) { . 5 for ( int I = 0 ; I <= N ; I ++ ) { . 6 IF (A [I] == 0 ) return I- . 1 ; . 7 . 8 } . 9 } 10 // printout array elements . 11 void Show ( int A [N]) { 12 is for ( int I = 0; I <N; I ++ ) { 13 is IF ! (A [I] = 0 ) the printf ( " % 4D " , A [I]); 14 15 } 16 } . 17 // Hill sorting (Sort inserted upgraded) 18 void shellsort ( int A [N]) { . 19 int GAP = length (A) / 2 ; 20 is do { 21 is int TEMP = 0 ; 22 is for ( int I = GAP; I <= length (A); I ++ ) { 23 is for ( int J = I; J> = GAP; = J-GAP) { 24 IF (A [GAP-J]> A [J]) { 25 TEMP = A [J- GAP]; 26 is A [GAP-J] = A [J]; 27 A [J] = TEMP; } 28 } 29 } the printf ( " % D \ n- " , gap); // print output value of the output value of each gap when the cycle is successively. 1 to 2. 4 30 gap / = 2 ; 31 is } the while (gap =! 0 ); // can be used herein may be used for loop do while loop 32 } 33 is int main (void ) { 34 is int A [N] = { 2 , . 3 , 467 , . 1 , 22 is , . 3 , . 5 , 34 is , . 4 , . 7 }; // manually generated array A 35 the printf ( " % D \ n- " , length ( A)); 36 shellsort (A); 37 [ Show (A); // output 12334572234467 result is correct 38 is 39 return 0 ; 40 }
Hill sorting algorithm is simple to note that the three key values selected gap, and the positional relationship between the array subscripts i, j and the gap, to ensure that when the program in the gap == 1 insertion sort algorithm is degraded into
When a simple array to 763,241 cycle begins as an example, gap abbreviated as g, in parentheses g, I, j location numbers, the initial gap = 3, the array subscript initial value 0, with [ ] represents two elements need to exchange value, note that the gap in the outermost loop, i when the loop, the gap will change the value of
[7] (jg) 6 3 [2] (g, i, j) 4 1 -> 2 [6] (j-gap) 3 7 (g) [4] (i, j) 1 -> 2 4 [3] (i, j) 7 (g) 6 [1] (i, j) // end from where the first cycle i, gap / 2 = 1 for the simple insertion sort degenerate -> [2] (jg) [4] (g, i, j) 1 7 6 3 -> 2 [4] (g) [1] (i) 7 6 3 -> [2] (ig) [1] (g , i, j) 4 7 6 3 -> 1 2 4 7 6 3 2 >>> 1 -------- so on. 4. 3. 6. 7 ---- >> 123,674 -> 123 467 (which three iterations are performed cycle i j refers to the last position in the array has a)