我这里有一个程序,允许用户输入随机生成的数字的N。现在,我在打印它时遇到了问题。它打印的不仅仅是执行时间。
void merge_sort(int i, int j, int a[], int aux[]) {
start = clock();
if (j <= i) {
// if the subsection is empty or a single element
return;
}
int mid = (i + j) / 2;
// left sub-array is a[i .. mid]
// right sub-array is a[mid + 1 .. j]
merge_sort(i, mid, a, aux); // sort the left sub-array recursively
merge_sort(mid + 1, j, a, aux); // sort the right sub-array recursively
int pointer_left = i; // pointer_left points to the beginning of the left sub-array
int pointer_right = mid + 1; // pointer_right points to the beginning of the right sub-array
int k; // k is the loop counter
// we loop from i to j to fill each element of the final merged array
for (k = i; k <= j; k++) {
if (pointer_left == mid + 1) { // left pointer has reached the limit
aux[k] = a[pointer_right];
pointer_right++;
} else if (pointer_right == j + 1) { // right pointer has reached the limit
aux[k] = a[pointer_left];
pointer_left++;
} else if (a[pointer_left] < a[pointer_right]) { // pointer left points to smaller element
aux[k] = a[pointer_left];
pointer_left++;
} else { // pointer right points to smaller element
aux[k] = a[pointer_right];
pointer_right++;
}
}
// copy the elements from aux[] to a[]
for (k = i; k <= j; k++) {
a[k] = aux[k];
}
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("TIME: %f\n", cpu_time_used);
}
// main method
int main(){
int size, i;
printf("Enter N: ");
scanf("%d", &size);
int array[size];
int aux[size];
if(size <= 0)
{
printf("\n Error!\n");
}
for (i = 0; i < size; i++)
{
array[i] = rand() % MAXRANGE;
}
printf("\nMerge Sorted: ");
merge_sort(0, size - 1, array, aux);
printArray(array, size);
return 0;
}我不知道在哪里放置clock()调用或计算执行时间。是印刷后的吗?
发布于 2022-03-31 14:18:41
以下是一些指导方针:
用于获得执行时间:
include <time.h>
int main(){
struct timeval stop,start;
int arr[10000];
gettimeofday(&start,NULL);
mergeSort(arr, 100);
gettimeofday(&stop,NULL);
printf("Time taken for Quick sort is: %ld microseconds\n",
(stop.tv_sec-start.tv_sec)*1000000+stop.tv_usec-start.tv_usec);
}https://stackoverflow.com/questions/60896690
复制相似问题