优化思路参考了该篇博客,写的很好,推荐阅读:冒泡排序算法优化
public class BubbleSort {
public static void bsa(int[] array){
int length = array.length;
int lastSortedIndex = length - 1;
for (int i=0;i<length;i++){
boolean isExchanged = false;
int tempLast = lastSortedIndex;
for (int j=0;j<lastSortedIndex;j++){
if (array[j] < array[j+1]){
int temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
isExchanged = true;
tempLast = j;
}
}
lastSortedIndex = tempLast;
if (!isExchanged){
break;
}
}
}
public static void main(String[] args) {
int[] array = {3,4,6,1,7,5,2,34,98};
bsa(array);
for (int i=0;i<array.length;i++){
System.out.println(array[i]);
}
}
}
实现流程:每一轮比较把最大(小)的值放到最后,下一轮比较长度减一
优化1:未完成全部循环次数时,数组可能已经有序,设置变量isExchanged
判断本轮是否进行了交换,如果没有发生交换,则证明数组已经有序,停止循环即可。
优化2:例如{3,4,5,1,2,6,7,34,98}
,若升序排列,很明显后四个值无需参与比较,因此每轮循环记录最后一次的发生交换的位置作为下一次的尾部边界,则可保证避免该位置之后所有满足条件的值参与比较。
时间复杂度:O(n²),优化后可达O(n)
空间复杂度:O(1)