优化后对已经排好序的数组排序的时间复杂度为O(1)
public class Test {
//冒泡排序
public static void main(String[] args) {
int arr[] = {1,2,3,4,5};
boolean flag = false;//假定数组是已经排好序的
for (int i = 0; i < arr.length-1; i++) {
System.out.println("========");
for (int j = 0; j < arr.length -1 -i; j++) {
if (arr[j]>arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] =temp;
flag = true;
}
}
if (flag == false) {
//假设成立,数组是有序的
break;
}else {
flag = false;
}
}
for (int i : arr) {
System.out.println(i);
}
}
}