我一直在计算这些排序算法所需的时间。我循环了所有的排序方法2000次,然后将总持续时间除以2000,以得到正确的持续时间值。问题是,它不能显示特定代码部分所需的确切时间。我的意思是,变量“duration”在程序流程中显示出递增的值。例如,对于N = 10000,“insertionSort()”给出0.000635,“mergeSort()”给出0.00836,“heapSort()”给出0.018485,而当我更改这些顺序时,“duration”仍会在程序中递增,无论算法类型如何。我尝试为每个过程提供不同的持续时间值,但那并没有起作用。有人能帮我理解这个问题吗?或者还有其他的时间测量方式吗?抱歉,如果这是一个愚蠢的问题,并且对我的语法差也很抱歉。
int main(){
srand(time(NULL));
int N, duration;
cout << endl << "N : ";
cin >> N; // N is array sze.
cout << endl;
// a4 would be the buffer array (for calculating proper duration).
int *a1 = new int[N];
int *a2 = new int[N];
int *a3 = new int[N];
int *a4 = new int[N];
cout << endl << "Unsorted array : " << endl;
for (int i = 0; i < N; i++){
a4[i] = rand() % 100;
cout << a4[i] << " ";
}
/*------------------------------------------------------------------------------*/
cout << endl << endl <<"Sorting with Insertion Sort, please wait..." << endl;
for(int i = 0; i < 2000; i++){
a1 = a4;
duration = clock();
insertionSort(a1, N - 1);
duration += clock() - duration;
}
cout << endl << "Insertion sort : " << endl;
print(a1, N);
cout << endl << endl << "Approximate duration for Insertion Sort : ";
cout << (double) (duration / 2000) / CLOCKS_PER_SEC;
cout << " s." << endl;
/*------------------------------------------------------------------------------*/
cout << endl << endl << "Sorting with Merge Sort, please wait..." << endl;
for(int i = 0; i < 2000; i++){
a2 = a4;
duration = clock();
mergeSort(a2, 0, N - 1);
duration += clock() - duration;
}
cout << endl << "Merge sort : " << endl;
print(a2, N);
cout << endl << endl << "Approximate duration for Merge Sort : ";
cout << (double) (duration / 2000) / CLOCKS_PER_SEC;
cout << " s."<< endl << endl;
/*------------------------------------------------------------------------------*/
cout << endl << endl << "Sorting with Heap Sort, please wait..." << endl;
for(int i = 0; i < 2000; i++){
a3 = a4;
duration = clock();
heapSort(a3, N);
duration += clock() - duration;
}
cout << endl << "Heap sort : " << endl;
print(a3, N);
cout << endl << endl << "Approximate duration for Heap Sort : ";
cout << (double) (duration / 2000) / CLOCKS_PER_SEC;
cout << " s."<< endl << endl;
return 0;
}