未优化
public static void bubbleSort2() {
int[] a = {11, 10, 20, 3, 8, 1, 5, 20, 12, 0};
int temp;
for (int i = 0; i < a.length - 1; i++) {
System.out.println("第"+(i+1)+"趟");
for (int j = 0; j < a.length - 1 - i;j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+"-");
}
}
优化后
public static void bubbleSort() {
int[] a = {1,2,3,4,5,6,7,8,9,10};
int temp;
int count=0;
boolean flag=false;
for (int i = 0; i < a.length - 1; i++) {
System.out.println("第"+(i+1)+"趟");
for (int j = 0; j < a.length - 1 - i;j++) {
System.out.println(count++);
if (a[j] > a[j + 1]) {
flag=true;
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
if(!flag){
break;
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+"-");
}
}