The hill sort is also one of the insertion sorts, but it is more efficient than the direct insertion sort.
The basic idea is:
First, take an integer less than n D1 as the first increment, grouping all the records in the file. All records with a multiple of D1 are placed in the same group. First, the direct insertion in each group is sorted;
Then, take the second increment d2< to repeat the above groupings and sorts until the increment dt=1 is taken.
The incremental sequence is particularly critical, with half of the general first-time sequence being incremented, and halving it later, until the increment is 1.
1#include <stdio.h>2#include <stdlib.h>3 4 intN;5 6 /*7 * Hill Sort8 */9 voidShellsort (int*Array)Ten { One intK = n/2;//incremental sequence (for example only) A while(k >0) - { - intI, J; the for(i = k +1; I <=n; i++) - { - if(Array[i] < array[i-K]) - { +array[0] =Array[i]; - for(j = i-k; J >0&& array[0] < ARRAY[J]; J-=k) + { AArray[j + K] =Array[j]; at } -Array[j + K] = array[0]; - } - } -K = k/2; - } in } - to intMain () + { - inti; the int*Array; *printf"Please enter the size of the array:"); $scanf"%d", &n);Panax NotoginsengArray = (int*)malloc(sizeof(int) * (n +1)); -printf"Please enter data (separated by spaces):"); the for(i =1; I <= N; i++) + { Ascanf"%d", &array[i]); the } + Shellsort (array); -printf"after sorting is:"); $ for(i =1; I <= N; i++) $ { -printf"%d", Array[i]); - } theprintf"\ n"); -}
The direct insert sort is stable, the worst time complexity is O (n^2), and the spatial complexity is O (1).
The hill sort is unstable, the time complexity is related to the increment sequence, and the increment sequence is taken to ensure that the value is not a common factor other than 1, and that the last increment must be 1.
Data structure sorting-hill sort