java實現快速排序

來源:互聯網
上載者:User

標籤: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實現快速排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.