首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何打印合并排序的执行时间

如何打印合并排序的执行时间
EN

Stack Overflow用户
提问于 2020-03-28 02:47:18
回答 1查看 1.4K关注 0票数 1

这里的示例程序输出

我这里有一个程序,允许用户输入随机生成的数字的N。现在,我在打印它时遇到了问题。它打印的不仅仅是执行时间。

代码语言:javascript
复制
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()调用或计算执行时间。是印刷后的吗?

EN

回答 1

Stack Overflow用户

发布于 2022-03-31 14:18:41

以下是一些指导方针:

用于获得执行时间:

代码语言:javascript
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60896690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档