Hill sorting is also called reduced incremental sorting.
Ideas
First divide the entire sequence of records to be sorted into several sub-sequences for direct insertion sorting respectively , and when the records in the entire sequence are "basically ordered", then perform direct insertion sorting for all records in sequence.
Code
voidshell_insert_sort(int a[],int n,int dk){
if(n <2){
return;}int index =1;for(int i = dk; i < n;++i){
if(a[i]< a[i - dk]){
int j = i - dk;// 有序序列结尾元素下标int val = a[i];// 待插入元素值while((j >=0)&&(a[j]> val)){
a[j + dk]= a[j];
j -= dk;}
a[j + dk]= val;}print(a, n, dk, index);++index;}}voidshell_sort(int a[],int n){
int dk = n /2;while(dk >=1){
shell_insert_sort(a, n, dk);
dk = dk /2;}}
test
Code
#include<iostream>usingnamespace std;voidprint(int a[],int num,int dk,int index){
cout <<"dk = "<< dk <<" index = "<< index <<" : ";for(int i =0; i < num;++i){
cout << a[i]<<" ";}
cout << endl;}intmain(){
int a[]={
7,6,5,4,3,2,1};shell_sort(a,sizeof(a)/sizeof(a[0]));
cin.get();return0;}
result
dk =3 index =1:4657321
dk =3 index =2:4357621
dk =3 index =3:4327651
dk =3 index =4:1324657
dk =1 index =1:1324657
dk =1 index =2:1234657
dk =1 index =3:1234657
dk =1 index =4:1234657
dk =1 index =5:1234567
dk =1 index =6:1234567