package wzs.sort;import java.util.Arrays;//雞尾酒排序,也就是定向冒泡排序, 雞尾酒攪拌排序, 攪拌排序 (也可以視作選擇排序的一種變形), //漣漪排序, 來回排序 or 快樂小時排序, 是冒泡排序的一種變形。此演算法與冒泡排序的不同處在於排序時是以雙向在序列中進行排序。public class Test_wzs002{ public static void main(String[] args) { int[] intArray = { 10, 3, 5, 7, 1, 9, 6, 2, 4, 8 }; cocktailSort(intArray); System.out.println("\n排序後:" + Arrays.toString(intArray)); } /** * 雞尾酒排序 * @param intArray */ private static void cocktailSort(int[] intArray) { int bottom = 0;// 索引開始位置 int top = intArray.length - 1;// 索引結束位置 boolean flag = true;// 控制排序停止 int count = 0;// 記錄排序次數 while (flag) { flag = false; // 從左至右,升序 for (int i = bottom; i < top; i++) { if (intArray[i] > intArray[i + 1]) { swap(intArray, i, i + 1); flag = true; } } top--; // 從右至左,降序 for (int j = top; j > bottom; j--) { if (intArray[j] < intArray[j - 1]) { swap(intArray, j, j - 1); flag = true; } } bottom++; count++;// 一次比較結束+1 System.out.println("第" + count + "次排序:" + Arrays.toString(intArray)); } } /** * 數組元素替換 * @param intArray 指定的數組 * @param i 待替換的下標 * @param j 替換的下標 */ private static void swap(int[] intArray, int i, int j) { int temp = intArray[i]; intArray[i] = intArray[j]; intArray[j] = temp; }}
輸出結果:
第1次排序:[1, 3, 5, 7, 2, 9, 6, 4, 8, 10]第2次排序:[1, 2, 3, 5, 4, 7, 6, 8, 9, 10]第3次排序:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]第4次排序:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]排序後:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]