/**
* 冒泡排序
*/
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int[] values={3,1,6,2,9,0,7,4,5,8};
int temp=0;
for(int i=0;i<values.length-1;i++){
boolean flag=true; //优化排序,减少不必要的比较
System.out.println("######"+"第"+(i+1)+"趟"+" "+"比较"+(values.length-i-1)+"次");
for(int j=0;j<values.length-1-i;j++){
if(values[j]>values[j+1]){
temp=values[j];
values[j]=values[j+1];
values[j+1]=temp;
flag=false;
}
System.out.println(Arrays.toString(values));
}
if(flag){
System.out.println("结束!!!");
break;
}
}
}
}
运行结果
######第1趟 比较9次
[1, 3, 6, 2, 9, 0, 7, 4, 5, 8]
[1, 3, 6, 2, 9, 0, 7, 4, 5, 8]
[1, 3, 2, 6, 9, 0, 7, 4, 5, 8]
[1, 3, 2, 6, 9, 0, 7, 4, 5, 8]
[1, 3, 2, 6, 0, 9, 7, 4, 5, 8]
[1, 3, 2, 6, 0, 7, 9, 4, 5, 8]
[1, 3, 2, 6, 0, 7, 4, 9, 5, 8]
[1, 3, 2, 6, 0, 7, 4, 5, 9, 8]
[1, 3, 2, 6, 0, 7, 4, 5, 8, 9]
######第2趟 比较8次
[1, 3, 2, 6, 0, 7, 4, 5, 8, 9]
[1, 2, 3, 6, 0, 7, 4, 5, 8, 9]
[1, 2, 3, 6, 0, 7, 4, 5, 8, 9]
[1, 2, 3, 0, 6, 7, 4, 5, 8, 9]
[1, 2, 3, 0, 6, 7, 4, 5, 8, 9]
[1, 2, 3, 0, 6, 4, 7, 5, 8, 9]
[1, 2, 3, 0, 6, 4, 5, 7, 8, 9]
[1, 2, 3, 0, 6, 4, 5, 7, 8, 9]
######第3趟 比较7次
[1, 2, 3, 0, 6, 4, 5, 7, 8, 9]
[1, 2, 3, 0, 6, 4, 5, 7, 8, 9]
[1, 2, 0, 3, 6, 4, 5, 7, 8, 9]
[1, 2, 0, 3, 6, 4, 5, 7, 8, 9]
[1, 2, 0, 3, 4, 6, 5, 7, 8, 9]
[1, 2, 0, 3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