直接上代碼
/**
*@Params :
*@Author :scy
*@Date :2019/6/20
* description:冒泡排序及其改進
*
*/
public static int[] bubbleSort(int[] array) {
int len = array.length;
int temp;
for (int i = 0;i<len-1;i++) {//循環lenth-1次
boolean isSorded = true;
for (int j = 0;j < len-1-i;j++) {//交換次數
if (array[j] > array[j+1]) {
isSorded = false;//如果交換了
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
if (isSorded) {
int num = i+1;
Log.d(TAG, "bubbleSort:發現" + num + "次時已經有序");
break;
}
}
return array;
}
//輸入
int[] array = {6,3,4,5};
//輸出
/com.scy.android.sortutil D/SortUtil: bubbleSort:發現2次時已經有序