【问题标题】:Timing a Bubble Sort定时冒泡排序
【发布时间】: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


【解决方案1】:

我认为您需要使用比 difftime 更精确的东西(仅以秒为单位报告):

请参阅:Time difference in C++ 了解更多信息。

【讨论】:

【解决方案2】:

它的执行速度比 cpu 时钟更新速度要快。你需要做的是执行你的排序几百万次,时间,然后将时间除以迭代次数(确保你使用双精度可以获得最高精度。所以基本上是这样的:

const int runs=1000000;
time(&start);

for(int r=0;r<runs;++r)
    bubbleSort(arr, 5000);

time(&end);
timeDiff = difftime(end, start);

double realduration=timeDiff/(double)runs;

【讨论】:

  • 虽然如此,但计时器精度为 1 秒,运行时间不到一秒(在上面的代码中添加冒泡排序实现并在我的笔记本电脑上运行),运行 10 天得到与使用更好的计时器相比,精度为 10 毫秒的输出似乎相当低效。或者运行 100 秒,你就知道你已经达到了 0.01 秒的精度。
  • 所呈现的循环的一个问题是,在第一次迭代之后,数组被排序。此后,您只需要计算气泡排序的最佳情况——一个已经排序的数组。
  • 由于 Sparky 已经指出,这不仅效率低下,而且是不正确的。
【解决方案3】:

5000 对于注册来说太小了,您需要运行整个排序过程 100 或 1000 次,然后除以该数字以获得一些时间

有人告诉我,要玩得开心,您需要让程序运行 5 到 10 秒

【讨论】:

    猜你喜欢
    • 2013-10-09
    • 2015-09-12
    • 1970-01-01
    • 2014-03-26
    • 2015-03-06
    • 2018-04-18
    • 2018-11-13
    • 2011-08-04
    • 2016-10-15
    相关资源
    最近更新 更多