类别:排序-交换排序参看 维基百科的定义
鸡尾酒排序 ,也就是定向冒泡排序 , 鸡尾酒搅拌排序 , 搅拌排序 (也可以视作选择排序 的一种变形), 涟漪排序 , 来回排序 or 快乐小时排序 , 是冒泡排序的一种变形。此算法与冒泡排序的不同处在于排序时是以双向在序列中进行排序。
using System; using System.Collections.Generic; namespace Com.Colobu.Algorithm.Exchange { /// <summary> /// <b>鸡尾酒排序</b>,也就是双向冒泡排序(bidirectional bubble sort), 鸡尾酒搅拌排序, 搅拌排序 /// (也可以视作选择排序的一种变形), 涟漪排序, 来回排序 or 快乐小时排序, /// 是冒泡排序的一种变形。 /// 此算法与冒泡排序的不同处在于排序时是以双向在序列中进行排序。 /// /// 平均时间复杂度:O(n^2) /// Stability:Yes /// </summary> public class CocktailSortAlgorithm { public static void CocktailSort<T>(IList<T> szArray) where T : IComparable { int bottom = 0; int top = szArray.Count - 1; bool swapped = true; while (swapped == true) // if no elements have been swapped, then the list is sorted { swapped = false; for (int i = bottom; i < top; i = i + 1) { if (szArray[i].CompareTo(szArray[i + 1]) > 0) // test whether the two elements are in the correct order { Swap(szArray,i,i + 1); // let the two elements change places swapped = true; } } // decreases top the because the element with the largest value in the unsorted // part of the list is now on the position top top = top - 1; for (int i = top; i > bottom; i = i - 1) { if (szArray[i].CompareTo(szArray[i - 1]) < 0) { Swap(szArray,i,i - 1); swapped = true; } } // increases bottom because the element with the smallest value in the unsorted // part of the list is now on the position bottom bottom = bottom + 1; } } private static void Swap<T>(IList<T> szArray, int i,int j) { T tmp = szArray[i]; szArray[i] = szArray[j]; szArray[j] = tmp; } } }
博客园 © 2004-2025 浙公网安备 33010602011771号 浙ICP备2021040463号-3