public class BubbleSort {
//冒泡排序
//基本思想:兩個數比較大小,較大的數下沉,較小的數冒起來
//過程:1.比較相鄰的兩個數,如果第二個數小就交換位置
//2.從後向前兩兩比較,一直到比較最前面的兩個數據。最終最小數被交換到起始的位置,
//這樣第一個最小數的位置就排好了
//繼續重複上述過程,依次將第2,3,...n-1個最小數排好位置
//平均時間複雜度爲:O(n^2)
public static void main(String[] args) {
int[] arr = new int[]{6,2,4,1,9,3,6,7,0};
System.out.println("排序前=====");
print(arr);
System.out.println("");
System.out.println("排序後");
long start1 = System.currentTimeMillis();
int[] result = BubbleSort(arr);
long end1 = System.currentTimeMillis();
System.out.println((end1-start1));
print(result);
System.out.println("");
System.out.println("優化後===");
long start2 = System.currentTimeMillis();
int[] result2 = BubbleSort2(arr);
long end2 = System.currentTimeMillis();
System.out.println((end2-start2));
print(result2);
}
public static int[] BubbleSort(int[] arr){
int temp;//臨時變量
for(int i=0; i<arr.length-1; i++){
for(int j=arr.length-1; j>i; j--){
if(arr[j]<arr[j-1]){
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
}
}
return arr;
}
//優化:
//針對問題:數據的順序排好後,冒泡算法仍會繼續進行下一輪的比較,直到arr.length-1次,後面的比較都是沒意義的。
//解決方案:
//設置標誌位flag,如果發生了交換flag設爲true,如果沒有交換flag設爲false
//這樣一輪比較結束後,如果flag仍未=爲false,即這一輪沒有發生交換,說明數據的順序已經排好了,沒有必要再繼續進行下去。
public static int[] BubbleSort2(int[] arr){
int temp = 0;
boolean flag = false;
for(int i=0; i<arr.length-1; i++){
for(int j=arr.length-1; j>i; j--){
if(arr[j]<arr[j-1]){
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
}
}
return arr;
}
public static void print(int[] arr){
for(int i=0; i<arr.length; i++){
System.out.print(arr[i]+",");
}
}
}