我正在编写一个程序,它将找出通过不同的排序过程需要多少毫秒才能找到最有效的。我无法从程序中获取正确的时间输出。而不是显示时间量,例如:
Bubble Sort: 100
Merge Sort: 45
etc.
我越来越:
Bubble Sort: -3098
Merge Sort: -3
etc.
如果有人可以帮助我弄清楚为什么会发生这种情况,我将不胜感激。这是我的源代码。
static double diffclock(clock_t clock1,clock_t clock2)
{
double diffticks=clock1-clock2;
double diffms=(diffticks)/(CLOCKS_PER_SEC/1000);
return diffms;
}
int main ()
{
clock_t begin, end;
for (int n = 1; n<=1000000; n*=10)
{
cerr << n << endl;
int *array = new int[n];
int *temparray = new int[n];
srand((unsigned int)time(0));
for (int i = 0; i < n; i++)
{
array[i] = rand()%1000;
}
begin = clock();
bubbleSort(array, n);
end = clock();
cerr << "Bubble Sort: " << diffclock(begin, end) << endl;
srand((unsigned int)time(0));
for (int i = 0; i < n; i++)
{
array[i] = rand()%1000;
}
begin = clock();
insertionSort(array, n);
end = clock();
cerr << "Insertion Sort: " << diffclock(begin, end) << endl;
srand((unsigned int)time(0));
for (int i = 0; i < n; i++)
{
array[i] = rand()%1000;
}
begin = clock();
mergesort(array, 0, n-1, temparray);
end = clock();
cerr << "Merge Sort: " << diffclock(begin, end) << endl;
srand((unsigned int)time(0));
for (int i = 0; i < n; i++)
{
array[i] = rand()%1000;
}
begin = clock();
quicksort(array, 0, n-1);
end = clock();
cerr << "Quick Sort: " << diffclock(begin, end) << endl;
srand((unsigned int)time(0));
for (int i = 0; i < n; i++)
{
array[i] = rand()%1000;
}
begin = clock();
selectionSort(array, n);
end = clock();
cerr << "Selection Sort: " << diffclock(begin, end) << endl;
}
return 0;
}
再次,任何帮助将不胜感激。