理论原理:
代码实现:
#include <iostream>
#include <windows.h>
#include <time.h>
using namespace std;
#define MAX 100000;
//希尔排序
void XiEr_Sort(int *arr,int length)
{
int increament=length;
int i,j,k;
do
{
increament=increament/3+1;
//一层循环分组
for(i=0;i<increament;i++)
{
//二层循环插入排序
for(j=i+increament;j<length;j+=increament)
{
int temp=arr[j];
//此处k一定要>=0 不然会漏算第一个数
for(k=j-increament;k>=0 && temp<arr[k];k-=increament)
{
arr[k+increament]=arr[k];
}
arr[k+increament]=temp;
}
}
}
//采用do while 可以在increament为1时进行一次插入排序
while(increament>1);
}
void printArr(int *arr,int length)
{
for(int i=0;i<length;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main()
{
int max=MAX;
srand(time(NULL));
int arr1[max];
int arr2[max];
for(int i=0;i<max;i++)
{
int r=rand()%max;
arr1[i]=r;
arr2[i]=r;
}
//获取系统时间
DWORD time_start,time_end;
time_start=GetTickCount();
XiEr_Sort(arr2,max);
time_end=GetTickCount();
cout<<"希尔排序"<<max<<"个数所需时间为"<<(time_end-time_start)<<endl;
return 0;
}
运行结果: