// shell_sort.cpp : 定义控制台应用程序的入口点。
//
#include<iostream>
using namespace std;
/*
*以一定步长对数组中数字进行排序(a:待排序数组,len:数组长度,inc:步长,b:单步步长排序后数组,left:步长余量)
*/
void step_insert_sort(int *a,int len,int inc,int *b,int left){
int step = len/inc;
int j = 0;
for(int i = 1;i < step;++i){
while((b[j*inc + left] <= a[i*inc + left])&&(j < i)){
++j;
}
if(j != i){
for(int m = i;m > j;--m){
b[(m)*inc + left] = b[(m - 1)*inc + left];
}
b[j*inc + left] = a[i*inc + left];
}else{
b[j*inc + left] = a[i*inc + left];
}
j = 0;
}
}
/*
*希尔排序算法实现,a:待排序数组,len:待续数组长度,inc:步长,b:单步步长排序后数组,
*排序过程数组a和数组b数据相互转移直到排序完毕,反会最后转移到的数组
*/
int *shell_sort(int *a,int len,int inc,int *b){
for(int i = 0;i < inc;++i){
b[i] = a[i];
step_insert_sort(a,len,inc,b,i);
}
for(int j = inc*(len/inc - 1);j < len; ++j){//数组末尾部分未被处理数据直接复制到数组b末尾
b[j] = a[j];
}
/*
*print for test
*
*for(int i = 0;i < len;++i){cout<<b[i]<<" ";}
*cout<<endl;
*/
if(inc == 1)return b;
inc = inc/2;
shell_sort(b,len,inc,a);
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[] = {6,2,3,4,5,1,7,8,9,7,16,12,13,10,15,11,17,18,5,13,21,22,23,24,25,26,27,28,29,30,31};
int *b = new int[31];
int *m = shell_sort(a,31,15,b);
for(int x = 0;x < 31;++x){
cout<<m[x]<<" "<<endl;
}
while(1);
return 0;
}