Reputation: 251
I want to calculate the time of bubble sort algorithm in C#. But it always give 0. This is my code.
public void bubbleSort(int[] arr, ref double time)
{
var sp = new Stopwatch();
sp.Start();
int temp = 0;
for (int i = 0; i < arr.Length; i++)
{
for (int sort = 0; sort < arr.Length - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}
sp.Stop();
time = sp.Elapsed.Milliseconds*1000;
}
in main the time is always 0. What mistake i have done in this code.
Upvotes: 3
Views: 317
Reputation: 10708
When you get Milliseconds
, you're only getting the millisecond component of the time. Thus, 1.0501s will only be listed as 50ms, not 1050.1ms. Also, since this returns an int
, you will not see fractional milliseconds, which may be the case for such a short algorythm.
Instead, use TotalMilliseconds
, which will return the entire time in units of milliseconds, as well as retuning a double
- which includes the fractional parts.
Upvotes: 5
Reputation: 133443
You need to use TotalMilliseconds
property
Gets the value of the current TimeSpan structure expressed in whole and fractional milliseconds.
time = sp.Elapsed.TotalMilliseconds * 1000;
Upvotes: 3