经典算法题每日演练——第二十四题 梳排序

  

  这篇再看看一个经典的排序,梳排序,为什么取名为梳,可能每个梳都有自己的gap吧,大梳子gap大一点,小梳子gap小一点。

上一篇我们看到鸡尾酒排序是在冒泡排序上做了一些优化,将单向的比较变成了双向,同样这里的梳排序也是在冒泡排序上做了一些优化。

冒泡排序上我们的选择是相邻的两个数做比较,就是他们的gap为1,其实梳排序提出了不同的观点,如果将这里的gap设置为一定的大小,

效率反而必gap=1要高效的多。

 下面我们看看具体思想,梳排序有这样一个1.3的比率值,每趟比较完后,都会用这个1.3去递减gap,直到gap=1时变成冒泡排序,这种

算法比冒泡排序的效率要高效的多,时间复杂度为O(N2/2p)  这里的p为增量,是不是跟希尔排序有点点神似。。。

    比如下面有一组数据: 初始化的gap=list.count/1.3, 然后用这个gap作为数组下标进行跨数字比较大小,前者大于后者则进行交换,

每一趟排序完成后都除以1.3, 最后一直除到gap=1

   

最后我们的数组就排序完毕了,下面看代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Xml.Xsl;
 6 
 7 namespace ConsoleApplication1
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             List<int> list = new List<int>() { 8, 1, 4, 2, 9, 5, 3 };
14 
15             Console.WriteLine("\n排序前 => {0}\n", string.Join(",", list));
16 
17             list = CombSort(list);
18 
19             Console.WriteLine("\n排序后 => {0}\n", string.Join(",", list));
20 
21             Console.Read();
22         }
23 
24         /// <summary>
25         /// 梳排序
26         /// </summary>
27         /// <param name="list"></param>
28         /// <returns></returns>
29         static List<int> CombSort(List<int> list)
30         {
31             //获取最佳排序尺寸: 比率为 1.3
32             var step = (int)Math.Floor(list.Count / 1.3);
33 
34             while (step >= 1)
35             {
36                 for (int i = 0; i < list.Count; i++)
37                 {
38                     //如果前者大于后者,则进行交换
39                     if (i + step < list.Count && list[i] > list[i + step])
40                     {
41                         var temp = list[i];
42 
43                         list[i] = list[i + step];
44 
45                         list[i + step] = temp;
46                     }
47 
48                     //如果越界,直接跳出
49                     if (i + step > list.Count)
50                         break;
51                 }
52 
53                 //在当前的step在除1.3
54                 step = (int)Math.Floor(step / 1.3);
55             }
56 
57             return list;
58         }
59     }
60 }

 

 

posted @ 2014-03-02 23:59  一线码农  阅读(5382)  评论(3编辑  收藏  举报