package sort;
public class BubbleSort {
public static void main(String[] args) {
int a[] = { 10, 8, 6, 2, 1, 3, 4, 5, 9, 0, 7 };
sort1(a);
A DD = new A();
System.out.println(a.length);
for (int i : a) {
System.out.println(i + "--");
}
}
private static void sort(int[] a) {
int lastExchangeIndex = a.length-1;// 优化第二点,减少每次内存循环次数
for (int i = 0; i < a.length; i++) {
boolean isSorted = true;//优化第一点,减少最外层循环的次数
for (int k = 0; k < lastExchangeIndex - 1; k++) {
if (a[k] > a[k + 1]) {
int temp = a[k + 1];
a[k + 1] = a[k];
a[k] = temp;
isSorted = false;
lastExchangeIndex = k;
}
}
if (isSorted) {
break;
}
}
}
}
解释sort的优化二,对于一个数组43215678
我们只需要对4321进行排序,5678不用修改它
lastExchangeIndex就是用来设置数字中 5的位置,每趟循环到5之前循环就可以了