package test;
public class BubbleSortTest {
//測試main方法
public static void main(String[] args){
int[] arr = {1,2,4,5,7,3,8,9,6,0};
BubbleSort(arr);
}
private static void BubbleSort(int a []){
int temp = 0; //臨時變量
int num = 0;//記錄總共冒泡次數
for (int i = 0; i < a.length ; i++) {
boolean flag = true;
for (int j = 0; j < a.length - i - 1; j++){
if (a[j]<a[j + 1]){ //把這裏改成大於,就是升序了
temp=a[j];
a[j]=a[j + 1];
a[j + 1]=temp;
flag = false;
}
}
System.out.print("第"+(i+1)+"次冒泡後,當前順序爲:");
for(int k=0;k<a.length;k++){
System.out.print(a[k]);
}
System.out.println();
num = i;
//flag爲true標誌當前冒泡次數已經將順序排好,跳出循環
if(flag){
break;
}
}
System.out.println("總共冒泡次數爲:"+(num+1));
}
}
運行結果如下:
第1次冒泡後,當前順序爲:2457389610
第2次冒泡後,當前順序爲:4573896210
第3次冒泡後,當前順序爲:5748963210
第4次冒泡後,當前順序爲:7589643210
第5次冒泡後,當前順序爲:7896543210
第6次冒泡後,當前順序爲:8976543210
第7次冒泡後,當前順序爲:9876543210
第8次冒泡後,當前順序爲:9876543210
總共冒泡次數爲:8