- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Xml.Xsl;
-
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- List<int> list = new List<int>() { 8, 1, 4, 2, 9, 5, 3 };
-
- Console.WriteLine("\n排序前 => {0}\n", string.Join(",", list));
-
- list = CockTailSort(list);
-
- Console.WriteLine("\n排序后 => {0}\n", string.Join(",", list));
-
- Console.Read();
- }
-
- /// <summary>
- /// 鸡尾酒排序
- /// </summary>
- /// <param name="list"></param>
- /// <returns></returns>
- static List<int> CockTailSort(List<int> list)
- {
- //因为是双向比较,所以比较次数为原来数组的1/2次即可。
- for (int i = 1; i <= list.Count / 2; i++)
- {
- //从前到后的排序 (升序)
- for (int m = i - 1; m <= list.Count - i; m++)
- {
- //如果前面大于后面,则进行交换
- if (m + 1 < list.Count && list[m] > list[m + 1])
- {
- var temp = list[m];
-
- list[m] = list[m + 1];
-
- list[m + 1] = temp;
- }
- }
-
- Console.WriteLine("正向排序 => {0}", string.Join(",", list));
-
- //从后到前的排序(降序)
- for (int n = list.Count - i - 1; n >= i; n--)
- {
- //如果前面大于后面,则进行交换
- if (n > 0 && list[n - 1] > list[n])
- {
- var temp = list[n];
-
- list[n] = list[n - 1];
-
- list[n - 1] = temp;
- }
- }
-
- Console.WriteLine("反向排序 => {0}", string.Join(",", list));
- }
-
- return list;
- }
- }
- }