對於冒泡排序的改進,感謝MoreWindows(微軟最有價值專家),給我提供這麼好的思路,我只是寫了一個完整的Java版本。
/** * * @author Fly */public class BubbleSort { //不加思考寫的交換排序 //不是冒泡排序,比較的不是相鄰的元素 public int[] bubbleSort(int[] a) { int size = a.length; for (int i = 0; i < size; i++) { for (int j = i + 1; j < size; j++) { if (a[i] > a[j]) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } } return a; } //冒泡排序 public int[] bubbleSort1(int[] a) { int size = a.length; for (int i = 0; i < size - i; i++) { for (int j = 0; j < size - i - 1; j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } return a; } //改進的冒泡排序 //改進點: //1)增加標誌位,標記最終的交換位置,去掉不必要的交換操作; //2)如果當前迴圈沒有交換資料,說明已經完成排序,去掉不必要的比較; public int[] bubbleSort2(int[] a) { int size = a.length; for (int i = 0; i < size - 1; i++) { //做一個標誌位 int flag = i; for (int j = 0; j < size - i - 1; j++) { //如果順序不對,記錄需要交換的標誌位,以後一次交換位置 if (a[j] > a[j + 1]) { flag = j; } } //如果標誌位更換說明資料順序不對 if (flag > i) { //交換資料 int temp = a[i]; a[i] = a[flag]; a[flag] = temp; //調整再次迴圈起始位置,因為標誌位以後的元素(假如有的話)肯定是順序的 i = flag; //如果標誌位沒有變化,那說明資料全部順位,直接跳出迴圈 } else { break; } } return a; } public void printArray(int[] a) { for (int i : a) { System.out.print(i + ","); } System.out.println(); } public static void main(String[] args) { int[] a = {2, 3, 1, 5, 7, 8, 9, 0, 11, 10, 12, 13, 14, 4, 6}; BubbleSort bubblesort = new BubbleSort(); bubblesort.printArray(a); bubblesort.printArray(bubblesort.bubbleSort(a)); bubblesort.printArray(bubblesort.bubbleSort1(a)); bubblesort.printArray(bubblesort.bubbleSort2(a)); }}