1 冒泡排序 class BubbleSorter { public static void Sort(int[] a) { BubbleSort(a); } private static void BubbleSort(int[] myArray) { for (int i = 0; i < myArray.Length ; i++) { for (int j=i;j<myArray .Length ;j++) if (myArray[i] > myArray[j]) { Swap(ref myArray[j], ref myArray[i]); } } } private static void Swap(ref int left, ref int right) { int temp; temp = left; left = right; right = temp; } } 2 鸡尾酒排序 class CockTailSorter { public static void CockTailSort(int[] myArray) { int low, up, index, i; low = 0; up = myArray.Length - 1; index = low; while (up > low) { for (i = low; i < up; i++) { if(myArray [i]>myArray [i+1]) { Swap (ref myArray [i],ref myArray [i+1]); index = i; } } up = index; //记录最后一个交换的位置 for (i = up; i > low; i--) { if (myArray[i] < myArray[i - 1]) { Swap(ref myArray[i],ref myArray[i - 1]); index = i; } } low = index; //记录最后一个交换的位置 } } private static void Swap(ref int left, ref int right) { int temp; temp = left; left = right; right = temp; } } 3 选择排序 class SelectSorter { private static void Swap(ref int left, ref int right) { int temp; temp = left; left = right; right = temp; } public static void SelectSort(int[] myArray) { int i, j, smallest; for (i = 0; i < myArray.Length - 1; i++) { smallest = i; //记录最小数据的下标 for (j = i + 1; j < myArray.Length; j++) { if (myArray[j] < myArray[smallest]) { smallest = j; //如果有它更小的数,将下标记录下来 } } Swap(ref myArray[i], ref myArray[smallest]); } } } 4 插入排序 class InsertSorter { public static void InsertSort(int[] myArray) { int i, j, temp; for (i = 1; i < myArray.Length; i++) { temp = myArray[i]; //保存当前数据 j = i - 1; //将数据插入到有序表中,如果表中的数据比该数据大那么就依次向后 //移动有序表中的数据,直到找到第一个比它小的数据将它放在那个数据后面 while (j >= 0 && myArray[j] > temp) { myArray[j + 1] = myArray[j]; j--; } myArray[j + 1] = temp; } } } 5 希尔排序 class ShellSorter { public static void ShellSort(int[] myArray) { int i, j, increment; int temp; for (increment = myArray.Length / 2; increment > 0; increment /= 2) { for (i = increment; i < myArray.Length; i++) { temp = myArray[i]; for (j = i; j >= increment; j -= increment) { if (temp < myArray[j - increment]) { myArray[j] = myArray[j - increment]; } else break; } myArray[j] = temp; } } } }