###### tags: `Java` # java自學紀錄 - 泡沫排序 ## 學習重點 * 排序 * 泡沫排序法 * swap ## 何謂排序 >將一序列的值由小排到大或由大排到小,稱為排序 ## swap >下圖為swap模板 ```java= import java.util.Scanner; public class Java_swap { static void swap(int a, int b){ int temp=a; //交換兩數 a=b; b=temp; System.out.println("a = "+a); System.out.println("b = "+b); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int a,b; a = in.nextInt(); b = in.nextInt(); swap(a,b); } } ``` >下圖為執行結果 ![](https://i.imgur.com/rE2Lrur.png) ## 泡沫排序法 > 從序列中第一筆資料逐一往後兩兩比較,若前者大於後者,則兩者交換 > 假如有一個```長度為N```的序列要進行排序,則應操作```N-1階```次的逐一比較 > 且每階次的逐一比較範圍均逐漸減一個,最後這個序列的資料會由小排到大 > 此方法即為```泡沫排序法``` ==example== ![](https://i.imgur.com/PQBRTyE.gif) 圖檔來源 : http://gg.gg/lnmiu ## Bubble Sort 實作 >輸入數字n >接著輸入n個數字 >輸出排序後的結果 >輸出交換了幾次 > ```java= import java.util.Scanner; public class Bubble_sort { public static void main(String[] args) { Scanner in = new Scanner(System.in); int bubble_sort[] = new int[100005]; int n; n = in.nextInt(); System.out.print("Before bubble sort : "); for(int i=1;i<=n;i++){ bubble_sort[i] = in.nextInt(); } int ans=0; for(int i=1;i<=n-1;i++){ for(int j=1;j<=n-i;j++){ if(bubble_sort[j]>bubble_sort[j+1]){ int temp= bubble_sort[j]; bubble_sort[j]=bubble_sort[j+1]; bubble_sort[j+1]=temp; ans++; //每交換一次ans就+1 } } } System.out.print("After bubble sort : "); for(int i=1;i<=n;i++){ System.out.print(bubble_sort[i]+" "); } System.out.println(); System.out.print("Number of swap : "+ans); } } ``` >下圖為執行結果 ![](https://i.imgur.com/mSlJYk3.png)