冒泡法数组排序与 System.Array.Sort()排序性能比较


今天看c#plus 中的一个比较冒泡排序与 System.Array.Sort() 性能,发现System.Arry.Sort()的性能要远远的优于冒泡排序,下面代码大家有兴趣可以看一下:

 1 using  System;
 2
 3 class  SortingCompetition
 4 {
 5    public static void BubbleSortAscending(int [] bubbles)
 6    {
 7        bool swapped = true;
 8
 9        for (int i=0;swapped ;i++ )
10        {
11            swapped = false;
12            for (int j = 0;j<(bubbles.Length-(i+1)) ;j++ )
13            {
14                if (bubbles[j]>bubbles[j+1])
15                {
16                    Swap(j,j+1,bubbles);
17                    swapped = true;
18                }

19            }

20        }

21    }

22
23    public static void Swap(int first,int second,int [] arr)
24    {
25        int temp;
26
27        temp = arr[first];
28        arr[first] = arr[second];
29        arr[second] = temp;
30    }

31
32    public static void PrintArray(int [] arr)
33    {
34        for (int i=0;i<arr.Length ;i++ )
35        {
36            Console.Write("{0}  ",arr[i]);
37        }

38    }

39
40    public static void Main()
41    {
42        int [] testScores = new int [200000];
43        DateTime sortStart;
44        DateTime sortEnd;
45
46        for (int i=0;i<testScores.Length ;i++ )
47        {
48            testScores[i] = testScores.Length-i;
49        }

50
51        Console.WriteLine("Now timing the bubble sort method please wait");
52        sortStart = DateTime.Now;
53        BubbleSortAscending(testScores);
54        sortEnd = DateTime.Now;
55        Console.WriteLine("Second elapsed bubble sorting an array of length {0}:{1}\n",testScores.Length,((sortEnd - sortStart).Ticks/10000000));
56        
57        //PrintArray(testScores);
58
59        for (int i=0;i<testScores.Length ;i++ )
60        {
61            testScores[i] = testScores.Length-i;
62        }

63
64        Console.WriteLine("\nNow timing the built in sort method of System.Array. Please wait");
65        sortStart = DateTime.Now;
66        Array.Sort(testScores);
67        sortEnd = DateTime.Now;
68        Console.WriteLine("Seconds elapsed .NET sorting an arry of length {0}:{1}\n",testScores.Length,(((sortEnd - sortStart).Ticks/10000000)));
69        
70        //PrintArray(testScores);
71    }

72}

上例中对一个长度为200000的数组进行排序,冒泡法用去107秒,System.Array.Sort()确用了不到1秒的时间,性能的差距太大了,有谁知道System.Array.Sort()用的什么排序法,欢迎大家讨论。

转载于:https://www.cnblogs.com/xiaotao823/archive/2008/01/28/1055407.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值