0

我正在编写一个程序,它将找出通过不同的排序过程需要多少毫秒才能找到最有效的。我无法从程序中获取正确的时间输出。而不是显示时间量,例如:

Bubble Sort: 100
Merge Sort: 45
etc.

我越来越:

Bubble Sort: -3098
Merge Sort: -3
etc.

如果有人可以帮助我弄清楚为什么会发生这种情况,我将不胜感激。这是我的源代码。

static double diffclock(clock_t clock1,clock_t clock2)
{
  double diffticks=clock1-clock2;
  double diffms=(diffticks)/(CLOCKS_PER_SEC/1000);
  return diffms;
}

int main ()
{
clock_t begin, end;

for (int n = 1; n<=1000000; n*=10)
{
    cerr << n << endl;
    int *array = new int[n];
    int *temparray = new int[n];

    srand((unsigned int)time(0));

    for (int i = 0; i < n; i++)
    {
        array[i] = rand()%1000;
    }

    begin = clock();
    bubbleSort(array, n);
    end = clock();
    cerr << "Bubble Sort: " << diffclock(begin, end) << endl;

    srand((unsigned int)time(0));

    for (int i = 0; i < n; i++)
    {
        array[i] = rand()%1000;
    }

    begin = clock();
    insertionSort(array, n);
    end = clock();
    cerr << "Insertion Sort: " << diffclock(begin, end) << endl;

    srand((unsigned int)time(0));

    for (int i = 0; i < n; i++)
    {
        array[i] = rand()%1000;
    }

    begin = clock();
    mergesort(array, 0, n-1, temparray);
    end = clock();
    cerr << "Merge Sort: " << diffclock(begin, end) << endl;

    srand((unsigned int)time(0));

    for (int i = 0; i < n; i++)
    {
        array[i] = rand()%1000;
    }

    begin = clock();
    quicksort(array, 0, n-1);
    end = clock();
    cerr << "Quick Sort: " << diffclock(begin, end) << endl;

    srand((unsigned int)time(0));

    for (int i = 0; i < n; i++)
    {
        array[i] = rand()%1000;
    }

    begin = clock();
    selectionSort(array, n);
    end = clock();
    cerr << "Selection Sort: " << diffclock(begin, end) << endl;
}

    return 0;
}

再次,任何帮助将不胜感激。

4

2 回答 2

3

你应该从clock1中减去clock2

static double diffclock(clock_t clock1,clock_t clock2)
{
   double diffticks=clock1-clock2;

或切换开始和结束

diffclock(begin, end) 

您的结束时间大于开始时间,因此如果减去(开始 - 结束),您会得到负值。

于 2013-03-04T21:15:39.097 回答
1

看起来你正在输出begin - end.

于 2013-03-04T21:15:30.027 回答