惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hugging Face - Blog
Hugging Face - Blog
云风的 BLOG
云风的 BLOG
大猫的无限游戏
大猫的无限游戏
M
MIT News - Artificial intelligence
L
LangChain Blog
阮一峰的网络日志
阮一峰的网络日志
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Recent Announcements
Recent Announcements
IT之家
IT之家
Google DeepMind News
Google DeepMind News
罗磊的独立博客
爱范儿
爱范儿
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
U
Unit 42
MongoDB | Blog
MongoDB | Blog
S
SegmentFault 最新的问题
B
Blog
博客园 - 叶小钗
月光博客
月光博客
Stack Overflow Blog
Stack Overflow Blog
V
Visual Studio Blog
C
Check Point Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

博客园 - smallnest

插入排序 Comb排序 Gnome sort 鸡尾酒排序 奇偶排序 快速排序 冒泡排序 algorithm in c# 开发人员最喜爱的十大免费的Visual Studio插件(下) 开发人员最喜爱的十大免费的Visual Studio插件(上) 一种获取重载泛型方法的方式 [游戏]五子连珠 发布一个记账软件---流水记账 轻松编写您自己的拖拉机算法,进行算法大战 拖拉机大战更新了 拖拉机大战1.1.0.320发布,更多新功能 拖拉机大战新春贺岁版发布 翻译助手0.1 visual studio 2005 常用类型的图标
希尔排序
smallnest · 2009-12-19 · via 博客园 - smallnest

希尔排序是一种插入排序法,它出自D.L.Shell,因此而得名。Shell排序又称作缩小增量排序。
  基本思想:
  不断把待排序的对象分成若干个小组,对同一小组内的对象采用直接插入法排序,当完成了所有对象都分在一个组内的排序后,排序过程结束。每次比较指定间距的两个数据项,若左边的值小于右边的值,则交换它们的位置。间距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