普通的冒泡排序:
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int a[] = { 4, 9, 2, 1, 6, 7, 8, 3, 10 };
int temp = 0;
int n = 0;
for (int i = 0; i < a.length - 1; i++) {
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;
}
n++;
}
}
System.out.println(Arrays.toString(a));
System.out.println("迭代次數:" + n);
}
}
結果:
[1, 2, 3, 4, 6, 7, 8, 9, 10]
迭代次數:36
優化後的冒泡排序:
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int a[] = { 4, 9, 2, 1, 6, 7, 8, 3, 10 };
int temp = 0;
int n=0;
for (int i = 0; i < a.length - 1; i++) {
boolean flag=true;
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;
flag=false;
}
n++;
}
if(flag) {
break;
}
}
System.out.println(Arrays.toString(a));
System.out.println("迭代次數:"+n);
}
}
結果:
[1, 2, 3, 4, 6, 7, 8, 9, 10]
迭代次數:33