我想对大输入实施计数排序以比较时间复杂度。我写了以下代码。它适用于小输入(int size = 50; size< = 500; size = size + 100)但是当我增加大小时(int size = 10000; size< = 100000; size = size + 50000)i无法得到正确的输出。需要帮助谢谢你。
#include <iostream>
#include<ctime>
#include<cstdlib>
#include<iomanip>
using namespace std;
void counting_sort(int a[], int size)
{
int i, j, k;
int idx = 0;
int low, high;
low = high = a[0];
for(i = 1; i < size; i++)
{
low = (a[i] < low) ? a[i] : low;
high = (a[i] > high) ? a[i] : high;
}
k = high - low + 1;
int *c = new int [k];
for(i = 0; i < k; i++) c[i] = 0;
for(i = 0; i < size; i++) c[a[i] - low]++;
for(i = low; i <= high; i++)
for(j = 0; j < c[i - low]; j++) a[idx++] = i;
for (int i = 0; i < size; i++ )
{
cout << a[i] << " ";
} delete [] c;
}
int main()
{
srand(time(0));
int*a;
double t1, t2;
for(int size = 50; size<=500; size= size+100)
{
a= new int[size];
for(int i=0;i<size;i++)
{
a[i]=rand()%10000;
}
t1=clock();
counting_sort(a, size-1);
t2=clock();
cout << setw(10) << (t2 - t1) / CLK_TCK << "sec\n" << endl;
delete[]a;
}
}
答案 0 :(得分:0)
Ideone问题。 Visual Studio工作正常。此外,counting_sort(a, size)
,而非size-1