又是一年
2012
2012
不断把待排序的对象分成若干个小组,对同一小组内的对象采用直接插入法排序,当完成了所有对象都分在一个组内的排序后,排序过程结束。每次比较指定间距 的两个数据项,若左边的值小于右边的值,则交换它们的位置。间距d按给定公式减少: di+1=(di +1)/2 ,直到d等于1为止。D可以选取{9,5,3,2,1}。
1 using System;
2 using System.Collections.Generic;
3
4 namespace Com.Colobu.Algorithm.Insertion
5 {
6 /// <summary>
7 /// <b>Shell sort</b> is a sorting algorithm that is a generalization of insertion sort,
8 /// with two observations:
9 /// insertion sort is efficient if the input is "almost sorted"
10 /// insertion sort is typically inefficient because it moves values just one position at a time.
11 ///
12 /// 对有n个元素的可比较资料,先取一个小于n的整数d1作为第一个增量,
13 /// 把文件的全部记录分成d1个组。
14 /// 所有距离为d1的倍数的记录放在同一个组中。
15 /// 先在各组内进行直接插入排序;然后,取第二个增量d2<d1
16 /// 重复上述的分组和排序,直至所取的增量dt=1(dt<dt-1<…<d2<d1),
17 /// 即所有记录放在同一组中进行直接插入排序为止。
18 /// 该方法实质上是一种分组插入方法。
19 ///
20 /// 平均时间复杂度:O(nlogn)
21 /// Stability:No
22 /// </summary>
23 public class ShellSortAlgorithm
24 {
25 public static void ShellSort<T>(IList<T> szArray) where T : IComparable
26 {
27 int i, j, k, gap;
28 T temp;
29
30 //gap sequence:a(n) = floor(fibonacci(n+1)^(1+sqrt(5)))
31 //the Fibonacci numbers (leaving out one of the starting 1's) to the power of twice the golden ratio
32 int[] gaps = { 1,5,13,43,113,297,815,1989,4711,11969,27901,84801,
33 213331,543749,1355339,3501671,8810089,21521774,
34 58548857,157840433,410151271,1131376761,2147483647 };
35
36 int n = szArray.Count;
37
38 //从素数序列中得到一个满足条件的最大的素数
39 for (k = 0; gaps[k] < n; k++) ;
40
41 while (--k >= 0)
42 {
43 gap = gaps[k]; //取增量
44
45 for (i = gap; i < n; i++) //按照此增量分组
46 {
47 temp = szArray[i];
48 j = i;
49 while (j >= gap && szArray[j - gap].CompareTo(temp) > 0) //将此组插入排序
50 {
51 szArray[j] = szArray[j - gap];
52 j = j - gap;
53 }
54 szArray[j] = temp;
55 }
56 }
57
58 }
59 }
60 }
61
1 using System;
2 using System.Collections.Generic;
3
4 namespace Com.Colobu.Algorithm.Insertion
5 {
6 /// <summary>
7 /// 插入排序(Insertion Sort)的算法描述是一种简单直观的排序算法。
8 /// 它的工作原理是通过构建有序序列,对于未排序数据,
9 /// 在已排序序列中从后向前扫描,找到相应位置并插入。
10 /// 插入排序在实现上,通常采用in-place排序(即只需用到O(1)的额外空间的排序),
11 /// 因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,
12 /// 为最新元素提供插入空间。
13 ///
14 /// 平均时间复杂度:O(n^2)
15 /// Stability:Yes
16 /// </summary>
17 public class InsertionSortAlgorithm
18 {
19 public static void InsertionSort<T>(IList<T> szArray) where T : IComparable
20 {
21 int count = szArray.Count;
22 int j;
23 T temp;
24 for (int i = 1; i < count; i++)
25 {
26 temp = szArray[i];//store the original sorted array in temp
27 for (j = i; j > 0 && (temp.CompareTo(szArray[j - 1]) < 0); j--)//compare the new array with temp
28 {
29 szArray[j] = szArray[j - 1];//all larger elements are moved one pot to the right
30 }
31 szArray[j] = temp;
32 }
33
34 }
35 }
36 }
37