首页 新闻 会员 周边

谁能解释一下这是为什么吗? 在同一个方法中,多次冒泡排序耗费时间递增

0
悬赏园豆:20 [已解决问题] 解决于 2013-09-23 10:29

代码很简单,多次执行冒泡排序,但是每一次排序都比上一次排序耗费的时间多,谁能解释一下这是为什么吗?

        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;
        }

执行结果,直接上图

HorsonJin的主页 HorsonJin | 初学一级 | 园豆:158
提问于:2013-09-23 10:05
< >
分享
最佳答案
0

楼主:你的Stopwatch类用错了,除了第一次,其余4次应该调用Restart方法,而不是Start方法,否则时间叠加了。今天受教了,没想到还有这么个计时用的类。。。。

收获园豆:10
会长 | 专家六级 |园豆:12401 | 2013-09-23 10:18
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册