1. 程式人生 > 其它 >氣泡排序的優化

氣泡排序的優化

氣泡排序的優化

 public static int[] sort(int[] arrays){
int temp;
for (int i = 0; i < arrays.length-1; i++) {
//外層迴圈,計算走了幾次
boolean flag =false;//判斷是否需要迴圈,減少沒必要的比較
for (int j = 0; j < arrays.length-1; j++) {
if (arrays[j+1]<arrays[j]){
temp=arrays[j];
arrays[j]=arrays[j+1];
arrays[j+1]=temp;
flag=true;
}
}
if (flag==false){
break;
}
}
return arrays;
}
}