C++实现的一段希尔排序代码

来源:互联网 发布:淘宝库存同步软件 编辑:程序博客网 时间:2024/06/02 06:51
#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 Sortfor (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;elsecout << "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;}

0 0