標籤:logs 最佳化 bool void stat public tmp turn dex
最佳化了一些細節,速度比上一個快排快10%
/** * @author CLY * 快速排序 */public class MyQuickSort { /** * 對待排數組排序(升序) * @param arr 待排數組 * @param pivot 樞軸在待排數組中的起始位置(排序起始位) * @param end 本次快排的結束位(排序結束位) */ public static void sort(int[] arr,int pivot,int end) { int tmp_pivot = pivot; int tmp_end = end; //為true時pivot在數組左邊,為false時在右邊 boolean flag = true; //整個過程是end往pivot逼近的過程 while (tmp_pivot!=tmp_end) { if (flag) {//pivot在左邊 while (tmp_pivot<tmp_end) { //如果成立,則樞軸被換到右邊,比樞軸小的數被換到左邊 if (arr[tmp_pivot]>arr[tmp_end]) { int tmp = arr[tmp_pivot]; arr[tmp_pivot] = arr[tmp_end]; arr[tmp_end] = tmp; int tmp_index = tmp_pivot; tmp_pivot = tmp_end; tmp_end = tmp_index; tmp_end++; break; }else {//尋找上一個右邊的數,看是否比樞軸小 tmp_end--; } } flag = false; }else {//pivot在右邊 while (tmp_pivot>tmp_end) { //如果成立,則樞軸被換到左邊,比樞軸大的數被換到左邊 if (arr[tmp_pivot]<arr[tmp_end]) { int tmp = arr[tmp_pivot]; arr[tmp_pivot] = arr[tmp_end]; arr[tmp_end] = tmp; int tmp_index = tmp_pivot; tmp_pivot = tmp_end; tmp_end = tmp_index; tmp_end--; break; }else {//尋找下一個左邊的數,看是否比樞軸大 tmp_end++; } } flag = true; } } //此時樞軸左邊的數都比它小,右邊的數都比它大。 //如果整個待排數組長度小於2,就表示已經排到底了。 if (end-pivot<2) { return; } //如果當前樞軸在起始點的右邊,就表示樞軸左邊有值,可以對左邊進行快排 if (tmp_pivot>pivot) { sort(arr, pivot, tmp_pivot-1);//對左邊的數進行快排 } //如果當前樞軸在結束點的左邊,就表示樞軸右邊有值,可以對右邊進行快排 if (tmp_pivot<end) { sort(arr, tmp_pivot+1, end);//對右邊的數進行快排 } }}
java實現快速排序