學習日記1 Arrays.sort()源碼解析


 /*
     * java1.7之后的版本,開始用雙軸快排取代了以前的排序算法,現在只實現了8種基本數據類型性的雙軸快排,對象的排序在1.7中還
     * 在用老式的,不過都標了過時,估計以后版本中就會被新的雙軸快排取代了。
     * 他的DualPivotQuicksort()方法,里邊一共寫了三種算法(不算改進版的插入排序話),對於大數組而且部分高度有序的用歸並排序,其余的用雙軸快排進行分割
     * 分割到足夠小的時候用插入排序(主要是改進版的pair insertion sort)。雙軸快排的基本原理是取兩個pivot,所有比pivot1小的放到最左邊,比pivot2
     * 大的放到最右邊,然后遞歸下去,就可以把兩端的元素完成排序,之后處理中間部分,中間部分如果過大就繼續遞歸用這種方式繼續分割,如果不大,就用單軸分割
     * 對兩部分遞歸調用下去。
     * 
     */
     /* 雙軸快排的測試數組
	int[] a = new int[300];
	for(int i=0;i<30;i++){
		a[i]=(int)(Math.random()*300);
	}
	sort(a);
     */
     /*  歸並排序算法的測試數組
	int[] a = new int[300];
	int[] b = new int[10];
	for(int i=0;i<30;i++){
		a[i]=(int)(Math.random()*300);
		for(int j=0;j<10;j++){
			a[i*10+j]=a[i]+j+1;
		}
	}
	sort(a);
     */
    /**
     * 升序排列指定數組.
     *
     *  這是由Vladimir Yaroslavskiy, Jon Bentley,Joshua Bloch這三個老外寫的雙
     * 軸快速排序算法實現的. 這種算法在處理某些數據集(比如某些會導致其他快排算法性能退化到n方)依舊保持了O(n log(n))
     * 的性能,而且他尤其比傳統的單軸快排要快
     *
     * @param a the array to be sorted
     */
    public static void sort(int[] a) {
        DualPivotQuicksort.sort(a);/*調用雙軸快排方法*/
    }

    /*
     * 符合類型的數組排序
     */

    /**
     * 后面的代碼基本都過時了,就不貼了,直接進正題看看排序的算法
     */
   
final class DualPivotQuicksort {

   
    private DualPivotQuicksort() {}


    /**
     * 這個指數組部分有序的值,也就是說,當數組本來是升序突然變成了降序或者等序,count值就+1,67指這種順序的變化次數不
     * 高於67次,也就是總體無序,部分有序的數組。
     */
    private static final int MAX_RUN_COUNT = 67;

    /**
     * 使用歸並排序相同元素的最大數目,如果相同元素多於這個數,那么還是用快排去排
     */
    private static final int MAX_RUN_LENGTH = 33;

    /**
     * 如果被排序數組的個數少於這個常量,就直接用快排的方法去排序
     */
    private static final int QUICKSORT_THRESHOLD = 286;

    /**
     * 如果被排序數組的個數少於47,就直接用插入排序排
     */
    private static final int INSERTION_SORT_THRESHOLD = 47;

    
    /*
     * 一些重載的方法
     */
    public static void sort(int[] a) {
        sort(a, 0, a.length - 1);
    }

    
    public static void sort(int[] a, int left, int right) {
       
        if (right - left < QUICKSORT_THRESHOLD) /*長度小於快排的那個值就用快排,不小於就繼續往下走,數值為286*/
            sort(a, left, right, true);
            return;
        }

       /*檢查一下這個數組是不是基本有序,運行機制是,用run來數組來順序的變化的點(比如正序變為逆序或等序,或者相反),
        count來記錄數組順序變化的次數,如果次數小說明數組高度有序,然后用下面的歸並排序來排,如果數字大說明數組高度無序
        就跳到雙軸快排來排序*/
        int[] run = new int[MAX_RUN_COUNT + 1];
        int count = 0; run[0] = left;

        for (int k = left; k < right; run[count] = k) {
            if (a[k] < a[k + 1]) { // 升序序列數
                while (++k <= right && a[k - 1] <= a[k]);
            } else if (a[k] > a[k + 1]) { // 降序虛列數
                while (++k <= right && a[k - 1] >= a[k]);
                for (int lo = run[count] - 1, hi = k; ++lo < --hi; ) {
                    int t = a[lo]; a[lo] = a[hi]; a[hi] = t;/*將原來的降序轉變為升序*/
                }
            } else { // equal
                for (int m = MAX_RUN_LENGTH; ++k <= right && a[k - 1] == a[k]; ) {
                    if (--m == 0) {
                        sort(a, left, right, true);
                        return;
                    }
                }
            }

            if (++count == MAX_RUN_COUNT) {
                sort(a, left, right, true);
                return;
            }
        }

        // 檢查一下特殊情況
        if (run[count] == right++) { // The last run contains one element
            run[++count] = right;
        } else if (count == 1) { // The array is already sorted
            return;
        }

        /*
         * 只有當數組很大(大於286),而且部分高度有序的時候,用下面的歸並排序排。
         * 下面聲明一個數組,歸並需要用到額外的數組*/
        int[] b; byte odd = 0;
        for (int n = 1; (n <<= 1) < count; odd ^= 1);

        if (odd == 0) {
            b = a; a = new int[b.length];
            for (int i = left - 1; ++i < right; a[i] = b[i]);
        } else {
            b = new int[a.length];
        }

        /* 歸並排序部分,這個地方就需要用到,前面用到的判斷是否部分高度有序的run數組和conut值,run數組代表部分有序的起止坐標,count代表無序的子序列數,
        *  而且這部分歸並用三層循環實現,並沒有用到遞歸,開銷要比遞歸小很多*/
        /* 思路是從run數組中取三個值,第一個值和第二個值為第一個有序子序列起始地址,第二個和第三個為第二個有序子序列,然后對這兩個子序列比較排序放到數組b中,
        *  這兩個有序子序列就合並為一個有序子序列,更新run數組和count的值,然后繼續往后取兩個子序列,繼續歸並,直到完成此次遍歷,然后根據新的run和count進
        *  行下一次歸並,直到count值小於等於1,表明數組已經排序完畢*/
        for (int last; count > 1; count = last) {
            for (int k = (last = 0) + 2; k <= count; k += 2) {
                int hi = run[k], mi = run[k - 1];
                for (int i = run[k - 2], p = i, q = mi; i < hi; ++i) {
                    if (q >= hi || p < mi && a[p] <= a[q]) {
                        b[i] = a[p++];
                    } else {
                        b[i] = a[q++];
                    }
                }
                run[++last] = hi;
            }
            /*count的值不為偶數時,那么最后一個有序子序列肯定沒參與到歸並里的,將沒參與歸並的數組完全復制到b中,參與下一輪的歸並*/
            if ((count & 1) != 0) {
                for (int i = right, lo = run[count - 1]; --i >= lo;
                    b[i] = a[i]
                );
                run[++last] = right;
            }
            int[] t = a; a = b; b = t;
        }
    }

    private static void sort(int[] a, int left, int right, boolean leftmost) {
        int length = right - left + 1;

        if (length < INSERTION_SORT_THRESHOLD) {/*數組特別小的就用插入排序,數值為47*/
            if (leftmost) {
                /*
                 * 所有的分割小塊中最左邊的一塊用傳統的插入排序來排序,只有1塊,其余所有用下面的pair insertion
                 * sort來排序
                 */
                for (int i = left, j = i; i < right; j = ++i) {
                    int ai = a[i + 1];
                    while (ai < a[j]) {
                        a[j + 1] = a[j];
                        if (j-- == left) {
                            break;
                        }
                    }
                    a[j + 1] = ai;
                }
            } else {
                /*
                 * 跳過有序的序列
                 */
                do {
                    if (left >= right) {
                        return;
                    }
                } while (a[++left] >= a[left - 1]);

                /*
                 * 每個邊界元素作為哨兵, 這樣每次迭代可以讓我們避免左側的檢查. 此外,我們用效率更高的算法, 也就是所謂的pair insertion
                 * sort, 比傳統的插入排序更快(PS:確實效率更高,比傳統的要少很多不必要的比較)。
                 */
                for (int k = left; ++left <= right; k = ++left) {
                    int a1 = a[k], a2 = a[left];

                    if (a1 < a2) {
                        a2 = a1; a1 = a[left];
                    }
                    while (a1 < a[--k]) {
                        a[k + 2] = a[k];
                    }
                    a[++k + 1] = a1;

                    while (a2 < a[--k]) {
                        a[k + 1] = a[k];
                    }
                    a[k + 1] = a2;
                }
                int last = a[right];

                while (last < a[--right]) {
                    a[right + 1] = a[right];
                }
                a[right + 1] = last;
            }
            return;
        }
        // 因為值近似的等於長度除以7,就取名seventh。可以的,這個起名給滿分
        int seventh = (length >> 3) + (length >> 6) + 1;

        /*
         * 對5個等間距的數組中心元素排序. 這些元素將作為下面描述的支點。
         * 根據經驗,這種選擇的方法會在處理大范圍輸入的時候更有效率
         */
        int e3 = (left + right) >>> 1; // 中指針
        int e2 = e3 - seventh;
        int e1 = e2 - seventh;
        int e4 = e3 + seventh;
        int e5 = e4 + seventh;

        /*對這5個元素用插入排序來排一排*/
        if (a[e2] < a[e1]) { int t = a[e2]; a[e2] = a[e1]; a[e1] = t; }

        if (a[e3] < a[e2]) { int t = a[e3]; a[e3] = a[e2]; a[e2] = t;
            if (t < a[e1]) { a[e2] = a[e1]; a[e1] = t; }
        }
        if (a[e4] < a[e3]) { int t = a[e4]; a[e4] = a[e3]; a[e3] = t;
            if (t < a[e2]) { a[e3] = a[e2]; a[e2] = t;
                if (t < a[e1]) { a[e2] = a[e1]; a[e1] = t; }
            }
        }
        if (a[e5] < a[e4]) { int t = a[e5]; a[e5] = a[e4]; a[e4] = t;
            if (t < a[e3]) { a[e4] = a[e3]; a[e3] = t;
                if (t < a[e2]) { a[e3] = a[e2]; a[e2] = t;
                    if (t < a[e1]) { a[e2] = a[e1]; a[e1] = t; }
                }
            }
        }

        // 指針們
        int less  = left;  // 中心部分的起始下標
        int great = right; // 右邊部分的起始下標(這兩個概念對照下面的那個圖看會好理解)
        if (a[e1] != a[e2] && a[e2] != a[e3] && a[e3] != a[e4] && a[e4] != a[e5]) {
            /*
             * 用5個元素中2,4個元素取出來作為指針,要注意的是 pivot1要小於pivot2.
             */
            int pivot1 = a[e2];
            int pivot2 = a[e4];

            /*
             * 第一個和最后一個元素來填兩個指針挪出來的坑,分割完畢后,兩個指針歸為,這就是他們倆的最終位置,而且不會再變也不用參加接下來的排序了
             */
            a[e2] = a[left];
            a[e4] = a[right];

            /*
             * 跳過左邊比pivot1小的元素和右邊比pivot大的元素,也就是這些元素不用動了,放在原地就好
             */
            while (a[++less] < pivot1);
            while (a[--great] > pivot2);

            /*
             * 分割:也就是小於pivot1的都放到左邊去,大於pivot2的都放到右邊去,用less和great來記錄兩邊的元素的分界下標
             *
             *   left part           center part                   right part
             * +--------------------------------------------------------------+
             * |  < pivot1  |  pivot1 <= && <= pivot2  |    ?    |  > pivot2  |
             * +--------------------------------------------------------------+
             *               ^                          ^       ^
             *               |                          |       |
             *              less                        k     great
             *
             * Invariants:
             *
             *              all in (left, less)   < pivot1
             *    pivot1 <= all in [less, k)     <= pivot2
             *              all in (great, right) > pivot2
             *
             * Pointer k is the first index of ?-part.
             */
            outer:
            for (int k = less - 1; ++k <= great; ) {
                int ak = a[k];
                if (ak < pivot1) { // Move a[k] to left part
                    a[k] = a[less];
                    /*
                     * 這里用 "a[i] = b; i++;" 而不是
                     *  "a[i++] = b;" 是性能問題,也就是這么寫運行快一點.
                     */
                    a[less] = ak;
                    ++less;
                } else if (ak > pivot2) { // Move a[k] to right part
                    while (a[great] > pivot2) {
                        if (great-- == k) {
                            break outer;
                        }
                    }
                    if (a[great] < pivot1) { // a[great] <= pivot2
                        a[k] = a[less];
                        a[less] = a[great];
                        ++less;
                    } else { // pivot1 <= a[great] <= pivot2
                        a[k] = a[great];
                    }
                    /*
                     * 這里用 "a[i] = b; i--;" 而不是
                     *  "a[i--] = b;" 因為性能問題.
                     */
                    a[great] = ak;
                    --great;
                }
            }

            // 把指針放在他們的最終位置
            a[left]  = a[less  - 1]; a[less  - 1] = pivot1;
            a[right] = a[great + 1]; a[great + 1] = pivot2;

            // 然后遞歸的對左邊部分和右邊部分排序,已經歸位的指針就不用加進去了
            sort(a, left, less - 2, leftmost);
            sort(a, great + 2, right, false);

            /*
             * 上邊的遞歸完事,左邊的和右邊就已經排完了,而且都在在自己該在的位置,接下來就是中間的部分,
             * 下面判斷中間部分范圍大小,如果大於七分之四(e1和e5的作用在這才看出來),就把所有和指針相等的元素也扔過去
             * 然后對這一部分遞歸,算法和上邊一模一樣,沒啥區別,只是<>改成了=
             */
            if (less < e1 && e5 < great) {
                
                while (a[less] == pivot1) {
                    ++less;
                }

                while (a[great] == pivot2) {
                    --great;
                }

                /*
                 * Partitioning:
                 *
                 *   left part         center part                  right part
                 * +----------------------------------------------------------+
                 * | == pivot1 |  pivot1 < && < pivot2  |    ?    | == pivot2 |
                 * +----------------------------------------------------------+
                 *              ^                        ^       ^
                 *              |                        |       |
                 *             less                      k     great
                 *
                 * Invariants:
                 *
                 *              all in (*,  less) == pivot1
                 *     pivot1 < all in [less,  k)  < pivot2
                 *              all in (great, *) == pivot2
                 *
                 * Pointer k is the first index of ?-part.
                 */
                outer:
                for (int k = less - 1; ++k <= great; ) {
                    int ak = a[k];
                    if (ak == pivot1) { // Move a[k] to left part
                        a[k] = a[less];
                        a[less] = ak;
                        ++less;
                    } else if (ak == pivot2) { // Move a[k] to right part
                        while (a[great] == pivot2) {
                            if (great-- == k) {
                                break outer;
                            }
                        }
                        if (a[great] == pivot1) { // a[great] < pivot2
                            a[k] = a[less];
                            
                            a[less] = pivot1;
                            ++less;
                        } else { // pivot1 < a[great] < pivot2
                            a[k] = a[great];
                        }
                        a[great] = ak;
                        --great;
                    }
                }
            }

            // Sort center part recursively
            sort(a, less, great, false);

        } else { 
            /*
             * 如果不算很大,就以中間那個數也就是e3位povit,用一樣的算法來排
             */
            int pivot = a[e3];

            /*
             * Partitioning degenerates to the traditional 3-way
             * (or "Dutch National Flag") schema:
             *
             *   left part    center part              right part
             * +-------------------------------------------------+
             * |  < pivot  |   == pivot   |     ?    |  > pivot  |
             * +-------------------------------------------------+
             *              ^              ^        ^
             *              |              |        |
             *             less            k      great
             *
             * Invariants:
             *
             *   all in (left, less)   < pivot
             *   all in [less, k)     == pivot
             *   all in (great, right) > pivot
             *
             * Pointer k is the first index of ?-part.
             */
            for (int k = less; k <= great; ++k) {
                if (a[k] == pivot) {
                    continue;
                }
                int ak = a[k];
                if (ak < pivot) { // Move a[k] to left part
                    a[k] = a[less];
                    a[less] = ak;
                    ++less;
                } else { // a[k] > pivot - Move a[k] to right part
                    while (a[great] > pivot) {
                        --great;
                    }
                    if (a[great] < pivot) { // a[great] <= pivot
                        a[k] = a[less];
                        a[less] = a[great];
                        ++less;
                    } else { 
                        a[k] = pivot;
                    }
                    a[great] = ak;
                    --great;
                }
            }
            sort(a, left, less - 1, leftmost);
            sort(a, great + 1, right, false);
        }
    }

    /**
     * Sorts the specified array.
     *
     * @param a the array to be sorted
     */
   

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM