Heisenberg
Heisenberg

Reputation: 37

Timing the efficiency of sorting algorithms but getting incorrect output

I'm writing a program that will find out how many milliseconds it takes to go through different sorting procedures in order to find the most efficient. I'm having trouble getting the correct time output from the program. Instead of displaying the amount of time such as:

Bubble Sort: 100
Merge Sort: 45
etc.

I'm getting:

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

If anyone can help me figure out why this is happening I'd really appreciate it. Here is my source code.

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;
}

Once again, any help would be greatly appreciated.

Upvotes: 0

Views: 165

Answers (2)

user1944441
user1944441

Reputation:

you should substract clock2 from clock1 in

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

or switch begin and end in

diffclock(begin, end) 

Your end time is larger that start time thus you get negative values if you subtract (start - end).

Upvotes: 3

Russell Zahniser
Russell Zahniser

Reputation: 16364

It looks like you're outputting begin - end.

Upvotes: 1

Related Questions