希尔排序基于插入排序。直接插入排序针对小众数据或有序数据时高效;希尔排序在逻辑上将数据划分为小众数据或较为有序的数据,以此提高效率
#include<vector>
#include<iostream>
using namespace std;
#include<stdio.h>
int cnt;
vector<int> G;
int n;
int m;
int A[1000000];
void insertionSort(int* A,int n,int g)
{
for(int i = g;i <= n-1;i++)
{
int v = A[i];
int j = i-g;
for(;j >= 0 && A[j] > v;)
{
A[j+g] = A[j];
cnt++;
j = j - g;
}
A[j+g] = v;
}
}
void shellSort(int* A,int n)
{
cnt = 0;
m = 0;
int h = 1;
G.push_back(h);
m++;
while(h*3+1 < n)
{
h = h*3 + 1;
G.push_back(h);
m++;
}
for(int i = m-1;i >= 0;i--)
{
insertionSort(A,n,G[i]);
}
}
int main()
{
cin >> n;
for(int i = 0;i < n;i++)
scanf("%d",&A[i]);
cnt = 0;
shellSort(A,n);
cout << G.size() << endl;
for ( int i = G.size() - 1;i >= 0;i-- ) {
printf("%d",G[i]);
if ( i ) printf(" ");
}
printf("\n");
printf("%d\n",cnt);
for ( int i = 0; i < n;i++) printf("%d\n",A[i]);
return 0;
}