#include <iostream>
#include "time.h"
#define Max 10
#include <sys/timeb.h>//获得时间
long getSystemTime(){
struct timeb tb;
ftime(&tb);
return tb.time*1000+tb.millitm;
}
void Swap(int* a,int *b){
int temp = *a;
*a = *b;
*b = temp;
}
void Shellsort(int arr[],int length){
int increasement = length;
int i,j,k;
do{
//确定分组的增量
increasement = increasement/3+1;
for(i = 0;i<increasement;i++){
for(j = i + increasement;j<length;j += increasement){//遍历分组后的元素
if(arr[j] < arr[j-increasement]){
int temp = arr[j];
for(k = j-increasement;k>=0 && temp<arr[k];k-=increasement){//分组后的移动
arr[k+increasement]=arr[k];
}
arr[k+increasement]=temp;
}
}
}
} while (increasement>1);//最后一次增量为1时统一进行插入排序
}
void PrintArray(int arr[],int length){
for(int i = 0;i<length;i++){
printf("%d",arr[i]);
}
printf("\n");
}
int main(){
int arr[Max];
srand((unsigned int)time(NULL));//产生随机数
for(int i = 0;i<Max;i++){
arr[i]=rand()%Max;
}
printf("排序前:\n");
PrintArray(arr,Max);
long tstart = getSystemTime();
Shellsort(arr,Max);
long tend = getSystemTime();
printf("希尔排序后:\n");
PrintArray(arr,Max);
printf("希尔排序%d个元素需要的时间是:%ld \n",Max,tend-tstart);
}```
![在这里插入图片描述](https://img-blog.csdnimg.cn/ab9dcfde02e847d8a7545241853c8df9.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBARGVsdGFkYXdu,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center)
希尔排序的实现
最新推荐文章于 2024-08-26 17:31:44 发布