大部分元素有序时
冒泡排序一样,还可以继续优化,用标识符标识出无序区与有序区界限位置,用一个变量记录最后一个变换的位置,有序区内的元素不再参与比较
public void sort() {
int[] array={2,3,4,5,6,7,8,9,1};
int lastRightExchangeIndex=0;
int lastLeftExchangeIndex=0;
int rightUnsortBorder = array.length-1;
int leftUnsortBorder = 0;
for(int i =0; i< array.length/2;i++){
boolean isSorted = true; //标记是否已经有序
//从左到右的循环
for(int j = i; j<rightUnsortBorder;j++){
if (array[j] > array[j+1]) {
int tem = array[j];
array[j]=array[j+1];
array[j+1] = tem;
isSorted=false;
lastRightExchangeIndex =j;
}
}
rightUnsortBorder = lastRightExchangeIndex;
if(isSorted){
break;
}
//从右到左的循环
isSorted=true;
for(int j = array.length-i-1;j>leftUnsortBorder;j--){
if(array[j]<array[j-1]){
int tem = array[j];
array[j]=array[j-1];
array[j-1] = tem;
isSorted=false;
lastLeftExchangeIndex = j;
}
}
leftUnsortBorder = lastLeftExchangeIndex;
if(isSorted){
break;
}
}
System.out.println(Arrays.toString(array));
}