## C ++ Shell sort

### C ++ Shell sort

``````#include <iostream>
#include <time.h>
#include <sys/timeb.h>

using namespace std;

#define MAX 10000

void SortArr(int arr[],int length) {
int i = 0, j = 0, k = 0;
int interval = length;
do
{
interval = interval / 3 + 1;//确定分组的增量
for (i = 0; i < interval; i++)//分组
{
for (j = i+ interval; j < length; j+= interval)//分组后根据分组的增量来排序
{
if (arr[j]<arr[j-interval])//当前元素与根据分组的增量前元素比较
{
int temp = arr[j];
for (k = j- interval; k >=0&& temp<arr[k]; k-= interval)//往当前元素的前面对比,直到比当前元素小
{
arr[k + interval] = arr[k];//满足条件则后移
}
arr[k + interval] = temp;//(不满足条件)在比当前元素小的元素的下一个位置插入
}
}
}
} while (interval>1);

}
void PrintArr(int arr[],int length) {
for (int i = 0; i < length; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}

long GetTime() {
timeb t;
ftime(&t);
return t.time * 1000 + t.millitm;
}
int main() {

srand((unsigned int)time(NULL));

int arr[MAX];

for (int i = 0; i < MAX; i++)
{
arr[i] = rand() % MAX;
}

//PrintArr(arr, MAX);

long after = GetTime();
SortArr(arr, MAX);
long before = GetTime();
//PrintArr(arr, MAX);

cout << "希尔排序" << MAX << "次，耗时:" << before - after << "毫秒" << endl;//1毫秒
return 0;
}

``````

Renderings:

### Guess you like

Origin blog.csdn.net/weixin_44567289/article/details/94960260
Recommended
Ranking
Daily