import java.util.Arrays;
/**
* This program demonstrates bubble sort. 冒泡排序的實現方式及優化,我的練習,若有錯誤請大俠指出
*/
public class BubbleSortImpro {
public static void main(String[] args) {
int[] a = { 3, 5, 10, 4, 1 };
bubbleSort1(a);
System.out.println("The 1 result: " + Arrays.toString(a));
int[] b = { 3, 5, 10, 4, 1 };
bubbleSort2(b);
System.out.println("The 2 result: " + Arrays.toString(b));
int[] c = { 3, 5, 10, 4, 1 };
bubbleSort3(c);
System.out.println("The 3 result: " + Arrays.toString(c));
}
// 第一種實現:(前兩種實現都是穩定排序)
private static void bubbleSort1(int[] arr) {
for (int i = 0; i < arr.length - 1; i++)
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = 0;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// 第二種實現:
private static void bubbleSort2(int[] arr) {
for (int i = arr.length - 1; i > 0; --i)
for (int j = 0; j < i; ++j) {
if (arr[j] > arr[j + 1]) {
int temp = 0;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// 第三種實現;省略了中間的屢次交換,這種實現使冒泡排序變成了不穩定排序(參考來的....)
private static void bubbleSort3(int[] arr) {
for (int i = arr.length - 1, max = 0; i > 0; max = 0, --i) {
for (int j = 1; j < i; ++j) {
if (arr[j] > arr[max])
max = j;
}
if (arr[max] > arr[i]) {
int temp = 0;
temp = arr[max];
arr[max] = arr[i];
arr[i] = temp;
}
}
}
}
Java初學者