【发布时间】:2019-03-07 07:43:14
【问题描述】:
我有 QuickSort 和 Test Class 用于这种排序。 秒表不工作,总是 0ms。
任务是实现指定的算法——将程序设计为控制台应用程序。我需要根据源数据的长度估计算法的执行时间。
快速排序
public static void Sorting(int[] array, int first, int last)
{
int x = array[(last - first) / 2 + first];
int temp;
int i = first;
int j = last;
while (i <= j)
{
while (array[i] < x && i <= last) ++i;
while (array[j] > x && j >= first) --j;
if (i<=j)
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
++i;
--j;
}
}
if (j > first)
{
Sorting(array, first, j);
}
if (i < last)
{
Sorting(array, i, last);
}
}
测试
class Program
{
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
int[] array = new int[20];
Random random = new Random();
for (int i=0; i<array.Length; i++)
{
array[i] = random.Next(1, 20);
}
Console.WriteLine("Sorting...");
stopwatch.Start();
for (int i=0; i < array.Length; i++)
{
QuickSort.Sorting(array, 0, array.Length - 1);
}
stopwatch.Stop();
Console.WriteLine("\nCheck:");
foreach (int x in array)
{
Console.WriteLine(x + "");
}
Console.WriteLine("Time: {0}ms", stopwatch.ElapsedMilliseconds);
stopwatch.Reset();
Console.ReadKey();
}
}
所有库都已连接。
【问题讨论】:
-
您是否考虑过您的代码执行时间不到 1 毫秒?
-
对于基准测试考虑使用 BenchmarkDotNet:github.com/dotnet/BenchmarkDotNet
-
秒表是非常原始的基准