【发布时间】:2011-06-25 19:24:25
【问题描述】:
我必须计算冒泡排序需要多长时间并打印它需要多长时间。在我的程序中,打印的时间始终为 0.00 秒。谁能告诉我我做错了什么?
int main()
{
srand((unsigned)time(NULL));
int arr[5000], arr2[5000];
int i;
time_t start, end;
double timeDiff;
for(i=0; i < 5000; i++)
{
arr[i] = rand() % 100 + 1;
arr2[i] = arr[i];
}
cout << "Here is the initial array:" << endl;
printArray(arr, 5000);
time(&start);
bubbleSort(arr, 5000);
time(&end);
timeDiff = difftime(end, start);
cout << "\nHere is the array after a bubble sort:" << endl;
printArray(arr, 5000);
cout << fixed << setprecision(2) << "\nIt took " << timeDiff << " seconds to bubble sort the array." << endl;
system("pause");
return 0;
}
【问题讨论】:
-
听起来 time_t 的粒度太大,无法捕获您的排序例程所花费的时间(即
bubbleSort执行时间不到 1 秒)。您需要多次运行该例程,以便它花费足够长的时间进行注册。 -
请注意,冒泡排序在计算机科学中没有任何地位,只能说明如何不做某事。
-
这是一个班级的作业。我们必须创建一个 5000 的数组并用数字 1-100 填充它,然后对其运行两种不同的排序方法。
标签: c sorting timing bubble-sort