Timing a Bubble Sort

I have to time how long a bubble sort takes and print how long it took. In my program the time printed is always 0.00 seconds. Can anyone tell me what I'm doing wrong?

Here is my main function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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;
}
The code looks right to me. Does bubbleSort() work?

You could always throw in a sleep( 2 ); after the call to bubbleSort(). Then difftime() should return at least 2 seconds.
closed account (zwA4jE8b)
you can use clock_t then divide the result by CLOCKS_PER_SECOND

this will actually return a value if the time is under 1 second.. i've noticed that time_t will not return any values less than one second.

and if you use this method, do not use the difftime function

Also an interesting thing to do is use three accumulators one for pass count, one for comparison count, and one for swap count to give you an idea of how much work is being done using the ineficient bubble sort.

1
2
3
4
5
6
7
clock_t start, end;
start = clock();

///blah blah code here

end = clock();
timediff = (end - start) / (double)CLOCKS_PER_SEC;
Last edited on
Topic archived. No new replies allowed.