代码很简单,多次执行冒泡排序,但是每一次排序都比上一次排序耗费的时间多,谁能解释一下这是为什么吗?
static void Main(string[] args) { for (int i = 1; i <= 5; i++) { Int32[] arr = new Int32[2000]; Int32[] arr1 = new Int32[2000]; Int32[] arr2 = new Int32[2000]; Int32[] arr3 = new Int32[2000]; Int32[] arr4 = new Int32[2000]; List<int> list = new List<int>(); for (int j = 0; j < 2000; j++) { arr[j] = j; arr1[j] = j; arr2[j] = j; arr3[j] = j; arr4[j] = j; } Console.WriteLine("\n第" + i + "轮比较:"); Stopwatch watch = new Stopwatch(); watch.Start(); BubbleSort(arr); watch.Stop(); Console.WriteLine("\n第一次冒泡排序耗费时间:" + watch.ElapsedMilliseconds); watch.Start(); BubbleSort(arr1); watch.Stop(); Console.WriteLine("\n第二次冒泡排序耗费时间:" + watch.ElapsedMilliseconds); watch.Start(); BubbleSort(arr2); watch.Stop(); Console.WriteLine("\n第三次冒泡排序耗费时间:" + watch.ElapsedMilliseconds); watch.Start(); BubbleSort(arr3); watch.Stop(); Console.WriteLine("\n第四次冒泡排序耗费时间:" + watch.ElapsedMilliseconds); watch.Start(); BubbleSort(arr4); watch.Stop(); Console.WriteLine("\n第五次冒泡排序耗费时间:" + watch.ElapsedMilliseconds); } Console.ReadKey(); } static int[] BubbleSort(int[] arr) { int temp; for (int i = 0; i < arr.Length; i++) { for (int j = arr.Length - 1; j > i; j--) { if (arr[j - 1] > arr[j]) { temp = arr[j - 1]; arr[j - 1] = arr[j]; arr[j] = temp; } } } return arr; }
执行结果,直接上图
楼主:你的Stopwatch类用错了,除了第一次,其余4次应该调用Restart方法,而不是Start方法,否则时间叠加了。今天受教了,没想到还有这么个计时用的类。。。。