【发布时间】:2017-01-12 07:21:45
【问题描述】:
到目前为止我的代码是这样的:
class Program
{
static void Main(string[] args)
{
Random r = new Random();
int n = r.Next(1, 10000);
int[] FortyKSet;
FortyKSet = new int[400];
for (int ndex = 0; ndex < FortyKSet.Length; ndex++)
{
FortyKSet[ndex] = r.Next(1, 80000);
}
int[] TenKSet;
TenKSet = new int[100];//populates the array with 100 integers
for (int index = 0; index < TenKSet.Length; index++)
{
TenKSet[index] = r.Next(1, 20000);//makes the 10,000 integers random
}
bubbleSort(TenKSet);
foreach (int i in TenKSet)
{
Console.Write(i + "," );
}
bubbleSort(FortyKSet);
foreach (int z in FortyKSet)
{
Console.Write(z + ",");
}
for (int space = 0; space < 2; space++)
{
Console.WriteLine("");
}
}
public static void swap(int[] array, int first, int second)
{
int temp = array[first];
array[first] = array[second];
array[second] = temp;
}
public static void bubbleSort(int[] array)
{
int start = 0;
bool swapMade = true;
while (start < array.Length - 1 && swapMade == true)
{
swapMade = false;
start++;
for (int first = 0; first < array.Length - start; first ++)
{
if(array[first] > array[first+1])
{
swap(array, first, first + 1);
swapMade = true;
}
}
}
DateTime begin = DateTime.Now;
TimeSpan time;
time = DateTime.Now.Subtract(begin);
Console.WriteLine("Time for bubblesort to complete: " + time.ToString(@"mm\:ss\.ffffff"));
}
}
当我运行程序时,它给了我两个排序的数组(应该如此。)在 TenKSet 数组上方,我得到了完成排序所花费的时间(同上。)但是当我运行 FortyKSet 时,它显示时间为 0。这是为什么呢?它不应该显示完成 TenKSet 所需的时间的两倍吗(我相信这里的大 O 表示法是 O(sqrt(n)),但我可能是错的。)
【问题讨论】:
-
这是很有趣的部分
DateTime begin = DateTime.Now; TimeSpan time; time = DateTime.Now.Subtract(begin);但这是最有趣的部分for (int space = 0; space < 2; space++) { Console.WriteLine(""); }。 -
我很惊讶您没有得到 0,因为您正在测量排序之后的时间:]
-
看看
Stopwatch类,它比DateTime更容易用于基准测试。特别是静态 StartNew 方法很有帮助:var stopwatch = Stopwatch.StartNew();msdn.microsoft.com/en-us/library/…