JDK(四)JDK1.8源碼分析【排序】DualPivotQuicksort


本文轉載自於曉飛93,原文鏈接 DualPivotQuickSort 雙軸快速排序 源碼 筆記

 

DualPivotQuicksort是Arrays類中提供的給基本類型的數據排序的算法。它針對每種基本數據類型都有對應的實現,實現方式有細微差異,但思路都是相同的,所以這里只挑選int類型的排序。

整個實現中的思路是:首先檢查數組的長度,比一個閾值小的時候直接使用雙軸快排。其它情況下,先檢查數組中數據的順序連續性。把數組中連續升序或者連續降序的信息記錄下來,順便把連續降序的部分倒置。這樣數據就被切割成一段段連續升序的數列。

如果順序連續性好,直接使用TimSort算法。TimSort算法的核心在於利用數列中的原始順序,所以可以提高很多效率。

順序連續性不好的數組直接使用了 雙軸快排 + 成對插入排序。成對插入排序是插入排序的改進版,它采用了同時插入兩個元素的方式調高效率。雙軸快排是從傳統的單軸快排到3-way快排演化過來的。參考:QUICKSORTING - 3-WAY AND DUAL PIVOT

final class DualPivotQuicksort {

    /**
     * Prevents instantiation.
     */
    private DualPivotQuicksort() {}

    /**
     * 待合並的序列的最大數量
     * The maximum number of runs in merge sort.
     */
    private static final int MAX_RUN_COUNT = 67;

    /**
     * 待合並的序列的最大長度
     * The maximum length of run in merge sort.
     */
    private static final int MAX_RUN_LENGTH = 33;

    /**
     * 如果參與排序的數組長度小於這個值,優先使用快速排序而不是歸並排序
     * If the length of an array to be sorted is less than this
     * constant, Quicksort is used in preference to merge sort.
     */
    private static final int QUICKSORT_THRESHOLD = 286;

    /**
     * 如果參與排序的數組長度小於這個值,優先考慮插入排序,而不是快速排序
     * If the length of an array to be sorted is less than this
     * constant, insertion sort is used in preference to Quicksort.
     */
    private static final int INSERTION_SORT_THRESHOLD = 47;

    /**
     * Sorts the specified range of the array using the given
     * workspace array slice if possible for merging
     *
     * @param a the array to be sorted
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
     * @param work a workspace array (slice)
     * @param workBase origin of usable space in work array
     * @param workLen usable size of work array
     */
    static void sort(int[] a, int left, int right,
                     int[] work, int workBase, int workLen) {
        // Use Quicksort on small arrays
        if (right - left < QUICKSORT_THRESHOLD) {
            sort(a, left, right, true);
            return;
        }

        /*
         * run[i] 意味着第i個有序數列開始的位置,(升序或者降序)
         * Index run[i] is the start of i-th run
         * (ascending or descending sequence).
         */
        int[] run = new int[MAX_RUN_COUNT + 1];
        int count = 0; run[0] = left;

        // 檢查數組是不是已經接近有序狀態
        // Check if the array is nearly sorted
        for (int k = left; k < right; run[count] = k) {
            if (a[k] < a[k + 1]) { // ascending 升序
                while (++k <= right && a[k - 1] <= a[k]);
            } else if (a[k] > a[k + 1]) { // descending 降序
                while (++k <= right && a[k - 1] >= a[k]);
                // 如果是降序的,找出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]; ) {
                    // 數列中有至少MAX_RUN_LENGTH的數據相等的時候,直接使用快排
                    if (--m == 0) {
                        sort(a, left, right, true);
                        return;
                    }
                }
            }

            /*
             * 數組並非高度有序,使用快速排序,因為數組中有序數列的個數超過了MAX_RUN_COUNT
             * The array is not highly structured,
             * use Quicksort instead of merge sort.
             */
            if (++count == MAX_RUN_COUNT) {
                sort(a, left, right, true);
                return;
            }
        }

        // 檢查特殊情況
        // Check special cases
        // Implementation note: variable "right" is increased by 1.
        if (run[count] == right++) { // The last run contains one element   // 最后一個有序數列只有最后一個元素
            run[++count] = right;   // 那給最后一個元素的后面加一個哨兵
        } else if (count == 1) { // The array is already sorted // 整個數組中只有一個有序數列,說明數組已經有序啦,不需要排序了
            return;
        }

        // Determine alternation base for merge
        byte odd = 0;
        for (int n = 1; (n <<= 1) < count; odd ^= 1);

        // 創建合並用的臨時數組
        // Use or create temporary array b for merging
        int[] b;                 // temp array; alternates with a
        int ao, bo;              // array offsets from 'left'
        int blen = right - left; // space needed for b
        if (work == null || workLen < blen || workBase + blen > work.length) {
            work = new int[blen];
            workBase = 0;
        }
        if (odd == 0) {
            System.arraycopy(a, left, work, workBase, blen);
            b = a;
            bo = 0;
            a = work;
            ao = workBase - left;
        } else {
            b = work;
            ao = 0;
            bo = workBase - left;
        }

        // 合並
        // 最外層循環,直到count為1,也就是棧中待合並的序列只有一個的時候,標志合並成功
        // a 做原始數組,b 做目標數組
        // Merging
        for (int last; count > 1; count = last) {
            // 遍歷數組,合並相鄰的兩個升序序列
            for (int k = (last = 0) + 2; k <= count; k += 2) {
                // 合並run[k-2] 與 run[k-1]兩個序列
                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 + ao] <= a[q + ao]) {
                        b[i + bo] = a[p++ + ao];
                    } else {
                        b[i + bo] = a[q++ + ao];
                    }
                }
                // 這里把合並之后的數列往前移動
                run[++last] = hi;
            }
            // 如果棧的長度為奇數,那么把最后落單的有序數列copy過對面
            if ((count & 1) != 0) {
                for (int i = right, lo = run[count - 1]; --i >= lo;
                    b[i + bo] = a[i + ao]
                );
                run[++last] = right;
            }
            // 臨時數組,與原始數組對調,保持a做原始數組,b 做目標數組
            int[] t = a; a = b; b = t;
            int o = ao; ao = bo; bo = o;
        }
    }

    /**
     * Sorts the specified range of the array by Dual-Pivot Quicksort.
     *
     * @param a the array to be sorted
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
     * @param leftmost indicates if this part is the leftmost in the range
     */
    private static void sort(int[] a, int left, int right, boolean leftmost) {
        int length = right - left + 1;

        // 小數組使用插入排序
        // Use insertion sort on tiny arrays
        if (length < INSERTION_SORT_THRESHOLD) {
            if (leftmost) {
                /*
                 * 經典的插入排序算法,不帶哨兵。做了優化,在leftmost情況下使用
                 * Traditional (without sentinel) insertion sort,
                 * optimized for server VM, is used in case of
                 * the leftmost part.
                 */
                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 {
                /*
                 * 首先跨過開頭的升序的部分
                 * Skip the longest ascending sequence.
                 */
                do {
                    if (left >= right) {
                        return;
                    }
                } while (a[++left] >= a[left - 1]);

                /*
                 * 這里用到了成對插入排序方法,它比簡單的插入排序算法效率要高一些
                 * 因為這個分支執行的條件是左邊是有元素的
                 * 所以可以直接從left開始往前查找
                 *
                 * Every element from adjoining part plays the role
                 * of sentinel, therefore this allows us to avoid the
                 * left range check on each iteration. Moreover, we use
                 * the more optimized algorithm, so called pair insertion
                 * sort, which is faster (in the context of Quicksort)
                 * than traditional implementation of insertion sort.
                 */
                for (int k = left; ++left <= right; k = ++left) {
                    int a1 = a[k], a2 = a[left];

                    // 保證a1>=a2
                    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;
        }

        // length / 7 的一種低復雜度的實現, 近似值(length * 9 / 64 + 1)
        // Inexpensive approximation of length / 7
        int seventh = (length >> 3) + (length >> 6) + 1;

        /*
         * 對5段靠近中間位置的數列排序,這些元素最終會被用來做軸(下面會講)
         * 他們的選定是根據大量數據積累經驗確定的
         *
         * Sort five evenly spaced elements around (and including) the
         * center element in the range. These elements will be used for
         * pivot selection as described below. The choice for spacing
         * these elements was empirically determined to work well on
         * a wide variety of inputs.
         */
        int e3 = (left + right) >>> 1; // The midpoint // 中間值
        int e2 = e3 - seventh;
        int e1 = e2 - seventh;
        int e4 = e3 + seventh;
        int e5 = e4 + seventh;

        // 插入排序
        // Sort these elements using insertion sort
        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; }
                }
            }
        }

        // 指針
        // Pointers
        int less  = left;  // The index of the first element of center part // 中間區域的首個元素的位置
        int great = right; // The index before the first element of right part //右邊區域的首個元素的位置

        if (a[e1] != a[e2] && a[e2] != a[e3] && a[e3] != a[e4] && a[e4] != a[e5]) {
            /*
             * 使用5個元素中的2,4兩個位置,他們兩個大致處在四分位的位置上
             * 需要注意的是pivot1 <= pivot2
             *
             * Use the second and fourth of the five sorted elements as pivots.
             * These values are inexpensive approximations of the first and
             * second terciles of the array. Note that pivot1 <= pivot2.
             */
            int pivot1 = a[e2];
            int pivot2 = a[e4];

            /*
             * The first and the last elements to be sorted are moved to the
             * locations formerly occupied by the pivots. When partitioning
             * is complete, the pivots are swapped back into their final
             * positions, and excluded from subsequent sorting.
             * 第一個和最后一個元素被放到兩個軸所在的位置。當階段性的分段結束后
             * 他們會被分配到最終的位置並從子排序階段排除
             */
            a[e2] = a[left];
            a[e4] = a[right];

            /*
             * Skip elements, which are less or greater than pivot values.
             * 跳過一些隊首的小於pivot1的值,跳過隊尾的大於pivot2的值
             */
            while (a[++less] < pivot1);
            while (a[--great] > pivot2);

            /*
             * Partitioning:
             *
             *   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];
                    /*
                     * Here and below we use "a[i] = b; i++;" instead
                     * of "a[i++] = b;" due to performance issue.
                     * 這里考慮的好細致,"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) { // k遇到great本次分割
                            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];
                    }
                    /*
                     * Here and below we use "a[i] = b; i--;" instead
                     * of "a[i--] = b;" due to performance issue.
                     * 同上,用"a[i]=b;i--"代替"a[i--] = b"
                     */
                    a[great] = ak;
                    --great;
                }
            } // 分割階段結束出來的位置,上一個outer結束的位置

            // 把兩個放在外面的軸放回他們應該在的位置上
            // Swap pivots into their final positions
            a[left]  = a[less  - 1]; a[less  - 1] = pivot1;
            a[right] = a[great + 1]; a[great + 1] = pivot2;

            // 把左邊和右邊遞歸排序,跟普通的快速排序差不多
            // Sort left and right parts recursively, excluding known pivots
            sort(a, left, less - 2, leftmost);
            sort(a, great + 2, right, false);

            /*
             * If center part is too large (comprises > 4/7 of the array),
             * swap internal pivot values to ends.
             * 如果中心區域太大,超過數組長度的 4/7。就先進行預處理,再參與遞歸排序
             * 預處理的方法是把等於pivot1的元素統一放到左邊,等於pivot2的元素統一
             * 放到右邊,最終產生一個不包含pivot1和pivot2的數列,再拿去參與快排中的遞歸
             */
            if (less < e1 && e5 < great) {
                /*
                 * Skip elements, which are equal to pivot values.
                 */
                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];
                            /*
                             * Even though a[great] equals to pivot1, the
                             * assignment a[less] = pivot1 may be incorrect,
                             * if a[great] and pivot1 are floating-point zeros
                             * of different signs. Therefore in float and
                             * double sorting methods we have to use more
                             * accurate assignment a[less] = a[great].
                             */
                            a[less] = pivot1;
                            ++less;
                        } else { // pivot1 < a[great] < pivot2
                            a[k] = a[great];
                        }
                        a[great] = ak;
                        --great;
                    }
                } // outer結束的位置
            }

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

        } else { // Partitioning with one pivot // 這里選取的5個元素剛好相等,使用傳統的3-way快排
            /*
             * Use the third of the five sorted elements as pivot.
             * This value is inexpensive approximation of the median.
             * 在5個元素中取中值
             */
            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]移動到左邊去,把center區向右滾動一個單位
                    a[k] = a[less];
                    a[less] = ak;
                    ++less;
                } else { // a[k] > pivot - Move a[k] to right part // 把a[k]移動到右邊
                    while (a[great] > pivot) {  // 先找到右邊最后一個比pivot小的值
                        --great;
                    }
                    if (a[great] < pivot) { // a[great] <= pivot    把他移到左邊
                        a[k] = a[less];
                        a[less] = a[great];
                        ++less;
                    } else { // a[great] == pivot   //如果相等,中心區直接擴展
                        /*
                         * Even though a[great] equals to pivot, the
                         * assignment a[k] = pivot may be incorrect,
                         * if a[great] and pivot are floating-point
                         * zeros of different signs. Therefore in float
                         * and double sorting methods we have to use
                         * more accurate assignment a[k] = a[great].
                         * 這里因為是整型值,所以a[k] == a[less] == pivot
                         */
                        a[k] = pivot;
                    }
                    a[great] = ak;
                    --great;
                }
            }

            /*
             * Sort left and right parts recursively.
             * All elements from center part are equal
             * and, therefore, already sorted.
             * 左右兩邊還沒有完全排序,所以遞歸解決
             * 中心區只有一個值,不再需要排序
             */
            sort(a, left, less - 1, leftmost);
            sort(a, great + 1, right, false);
        }
    }
}

 


免責聲明!

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



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