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

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
月光博客
月光博客
爱范儿
爱范儿
The Cloudflare Blog
Y
Y Combinator Blog
B
Blog RSS Feed
Stack Overflow Blog
Stack Overflow Blog
博客园 - 叶小钗
G
Google Developers Blog
J
Java Code Geeks
P
Proofpoint News Feed
美团技术团队
Engineering at Meta
Engineering at Meta
腾讯CDC
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园_首页
WordPress大学
WordPress大学
博客园 - 聂微东
雷峰网
雷峰网
有赞技术团队
有赞技术团队
L
LangChain Blog
N
Netflix TechBlog - Medium
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 【当耐特】

博客园 - 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

类别:排序-交换排序
参看 维基百科的定义

鸡尾酒排序,也就是定向冒泡排序, 鸡尾酒搅拌排序, 搅拌排序 (也可以视作选择排序的一种变形), 涟漪排序, 来回排序 or 快乐小时排序, 是冒泡排序的一种变形。此算法与冒泡排序的不同处在于排序时是以双向在序列中进行排序。

1 using System;
2  using System.Collections.Generic;
3
4 namespace Com.Colobu.Algorithm.Exchange
5 {
6 /// <summary>
7 /// <b>鸡尾酒排序</b>,也就是双向冒泡排序(bidirectional bubble sort), 鸡尾酒搅拌排序, 搅拌排序
8 /// (也可以视作选择排序的一种变形), 涟漪排序, 来回排序 or 快乐小时排序,
9 /// 是冒泡排序的一种变形。
10 /// 此算法与冒泡排序的不同处在于排序时是以双向在序列中进行排序。
11 ///
12 /// 平均时间复杂度:O(n^2)
13 /// Stability:Yes
14 /// </summary>
15 public class CocktailSortAlgorithm
16 {
17 public static void CocktailSort<T>(IList<T> szArray) where T : IComparable
18 {
19 int bottom = 0;
20 int top = szArray.Count - 1;
21 bool swapped = true;
22 while (swapped == true) // if no elements have been swapped, then the list is sorted
23 {
24 swapped = false;
25 for (int i = bottom; i < top; i = i + 1)
26 {
27 if (szArray[i].CompareTo(szArray[i + 1]) > 0) // test whether the two elements are in the correct order
28 {
29 Swap(szArray,i,i + 1); // let the two elements change places
30 swapped = true;
31 }
32 }
33 // decreases top the because the element with the largest value in the unsorted
34 // part of the list is now on the position top
35 top = top - 1;
36 for (int i = top; i > bottom; i = i - 1)
37 {
38 if (szArray[i].CompareTo(szArray[i - 1]) < 0)
39 {
40 Swap(szArray,i,i - 1);
41 swapped = true;
42 }
43 }
44 // increases bottom because the element with the smallest value in the unsorted
45 // part of the list is now on the position bottom
46 bottom = bottom + 1;
47 }
48 }
49
50 private static void Swap<T>(IList<T> szArray, int i,int j)
51 {
52 T tmp = szArray[i];
53 szArray[i] = szArray[j];
54 szArray[j] = tmp;
55 }
56 }
57 }
58