#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
void ShellSort(int *a, int n)
{
int d;
d = n / 2;
while (d >= 1)
{
for (int i = 0; i < d; i++)
{
for (int j = i; j < n; j += d)
{
//Insert Sort
for (int k = i; k < j; k += d)
{
if (a[j] < a[k])
{
int tmpJ = a[j];
for (int p = j; p > k; p -= d)
{
a[p] = a[p - d];
}
a[k] = tmpJ;
}
}
}
}
d /= 2;
}
}
void Print(int *a, int n)
{
bool correct = true;
for (int i = 0; i < n; i++)
{
if (i<n - 1 && a[i]>a[i + 1])
{
correct = false;
}
cout << a[i] << " ";
}
cout << endl;
if (correct)
cout << "correct" << endl;
else
cout << "wrong" << endl;
}
int main()
{
const int max = 100;
const int testCases = 10;
int *a = new int[max];
srand(time(NULL));
int count = 0;
while (count++ < testCases){
for (int i = 0; i < max; i++)
{
a[i] = rand() % 1000;
}
ShellSort(a, max);
Print(a, max);
cout << endl;
}
delete []a;
return 0;
}
C++实现的一段希尔排序代码
最新推荐文章于 2023-10-04 13:17:10 发布