排序八:鸡尾酒排序
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace CocktailSort 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 int[] arr = new int[100]; 14 Random rd = new Random(); 15 for (int i = 0; i < arr.Length; i++) 16 { 17 arr[i] = rd.Next(100); 18 } 19 Sort(arr); 20 } 21 22 public static void Sort(int[] arr) 23 { 24 //需要来回arr.Length/2趟 25 for (int i = 0; i < arr.Length / 2; i++) 26 { 27 //类冒泡,交换最大值至右端 28 for (int j = i; j < arr.Length - i - 1; j++) 29 if (arr[j] > arr[j + 1]) 30 Swap(arr, j, j + 1); 31 //类冒泡,交换最小值至左端 32 for (int j = arr.Length - i - 1; j > i; j--) 33 if (arr[j] < arr[j - 1]) 34 Swap(arr, j, j - 1); 35 } 36 foreach (int i in arr) 37 Console.WriteLine(i); 38 } 39 40 public static void Swap(int[] arr, int left, int right) 41 { 42 int temp = arr[left]; 43 arr[left] = arr[right]; 44 arr[right] = temp; 45 } 46 } 47 }