讓面試官滿意的排序算法(圖文解析)

讓面試官滿意的排序算法(圖文解析)

  • 這種排序算法可以讓面試官面露微笑
  • 這種排序算法集各排序算法之大成
  • 這種排序算法邏輯性十足
  • 這種排序算法可以展現本身對Java底層的瞭解

    這種排序算法出自Vladimir Yaroslavskiy、Jon Bentley和Josh Bloch三位大牛之手,它就是JDK的排序算法——java.util.DualPivotQuicksort(雙支點快排)java

DualPivotQuicksort

先看一副邏輯圖(若有錯誤請大牛在評論區指正)面試

插排指的是改進版插排—— 哨兵插排

快排指的是改進版快排——雙支點快排算法

DualPivotQuickSort沒有Object數組排序的邏輯,此邏輯在Arrays中,好像是歸併+Tim排序segmentfault

圖像應該很清楚:對於不一樣的數據類型,Java有不一樣的排序策略:數組

  • byte、short、char 他們的取值範圍有限,使用計數排序佔用的空間也不過256/65536個單位,只要排序的數量不是特別少(有一個計數排序閾值,低於這個閾值的話就沒有不要用空間換時間了),都應使用計數排序
  • int、long、float、double 他們的取值範圍很是的大,不適合使用計數排序
  • float和double 他們又有特殊狀況:app

    • NAN(not a number),NAN不等於任何數字,甚至不等於本身
    • +0.0,-0.0,float和double沒法精確表示十進制小數,咱們所看到的十進制小數其實都是取得近似值,於是會有+0.0(接近0的正浮點數)和-0.0(接近0的負浮點數),在排序流程中統一按0來處理,於是最後要調整一下-0.0和+0.0的位置關係
  • Object

計數排序

計數排序是以空間換時間的排序算法,它時間複雜度O(n),空間複雜度O(m)(m爲排序數值可能取值的數量),只有在範圍較小的時候才應該考慮計數排序less

(源碼以short爲例)工具

int[] count = new int[NUM_SHORT_VALUES]; //1 << 16 = 65536,即short的可取值數量

//計數,left和right爲數組要排序的範圍的左界和右界
//注意,直接把
for (int i = left - 1; ++i <= right;count[a[i] - Short.MIN_VALUE]++);

//排序
for (int i = NUM_SHORT_VALUES, k = right + 1; k > left; ) {
    while (count[--i] == 0);
    short value = (short) (i + Short.MIN_VALUE);
    int s = count[i];

    do {
        a[--k] = value;
    } while (--s > 0);
}

哨兵插排

當數組元素較少時,時間O(n^2^)和O(log~n~)其實相差無幾,而插排的空間佔用率要少於快排和歸併排序,於是當數組元素較少時(<插排閾值),優先使用插排優化

哨兵插排是對插排的優化,原插排每次取一個值進行遍歷插入,而哨兵插排則取兩個,較大的一個(小端在前的排序)做爲哨兵,當哨兵遍歷到本身的位置時,另外一個值能夠直接從哨兵當前位置開始遍歷,而不用再重頭遍歷ui

只畫了靜態圖,若是有好的繪製Gif的工具請在評論區告訴我哦

咱們來看一下源碼:

if (leftmost) {
    //傳統插排(無哨兵Sentinel)
    //遍歷
    //循環向左比較(<左側元素——換位)-直到大於左側元素
    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]);

    //以兩個爲單位遍歷,大的元素充當哨兵,以減小小的元素循環向左比較的範圍
    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;

雙支點快排

重頭戲:雙支點快排!

快排雖然穩定性不如歸併排序,可是它不用複製來複制去,省去了一段數組的空間,在數組元素較少的狀況下穩定性影響也會降低(>插排閾值 ,<快排閾值),優先使用快排

雙支點快排在原有的快排基礎上,多加一個支點,左右共進,效率提高

看圖:

  1. 第一步,取支點

    注意:若是5個節點有相等的任兩個節點,說明數據不夠均勻,那就要使用單節點快排
  2. 快排

源碼(int爲例,這麼長估計也沒人看)

// Inexpensive approximation of length / 7 
// 快排閾值是286 其7分之一小於等於1/8+1/64+1
int seventh = (length >> 3) + (length >> 6) + 1;

// 獲取分紅7份的五個中間點
int e3 = (left + right) >>> 1; // The midpoint
int e2 = e3 - seventh;
int e1 = e2 - seventh;
int e4 = e3 + seventh;
int e5 = e4 + seventh;

// 保證中間點的元素從小到大排序
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]) {
    /*
             * 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];

    while (a[++less] < pivot1);
    while (a[--great] > pivot2);

    /*
             * Partitioning:
             *
             *   left part           center part                   right part
             * +--------------------------------------------------------------+
             * |  < pivot1  |  pivot1 <= && <= pivot2  |    ?    |  > pivot2  |
             * +--------------------------------------------------------------+
             *               ^                          ^       ^
             *               |                          |       |
             *              less                        k     great
             */
    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[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];
            }
            /*
                     * Here and below we use "a[i] = b; i--;" instead
                     * of "a[i--] = b;" due to performance issue.
                     */
            a[great] = ak;
            --great;
        }
    }

    // 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.
             */
    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;
            }
        }
    }

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

} else { // Partitioning with one pivot
    /*
             * Use the third of the five sorted elements as pivot.
             * This value is inexpensive approximation of the median.
             */
    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[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] = 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);
}

歸併排序

你不會覺得元素多(>快排閾值)就必定要用歸併了吧?

錯!元素多時確實對算法的穩定性有要求,但是若是這些元素可以穩定快排呢?

開發JDK的大牛顯然考慮了這一點:他們在歸併排序以前對元素進行了是否能穩定快排的判斷:

  • 若是數組自己幾乎已經排好了(能夠看出幾段有序數組的拼接),那還排什麼,理一理返回就好了
  • 若是出現連續33個相等元素——使用快排(實話說,我沒弄明白爲何,有無大牛給我指點迷津?)
//判斷結構是否適合歸併排序
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]);
        for (int lo = run[count] - 1, hi = k; ++lo < --hi; ) {
            int t = a[lo]; a[lo] = a[hi]; a[hi] = t;
        }
    } else { 
        //連續MAX_RUN_LENGTH(33)個相等元素,使用快排
        for (int m = MAX_RUN_LENGTH; ++k <= right && a[k - 1] == a[k]; ) {
            if (--m == 0) {
                sort(a, left, right, true);
                return;
            }
        }
    }

    //count達到MAX_RUN_LENGTH,使用快排
    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;
}

歸併排序源碼

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;
}

// Merging
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 + ao] <= a[q + ao]) {
                b[i + bo] = a[p++ + ao];
            } else {
                b[i + bo] = a[q++ + ao];
            }
        }
        run[++last] = hi;
    }
    if ((count & 1) != 0) {
        for (int i = right, lo = run[count - 1]; --i >= lo;
             b[i + bo] = a[i + ao]
            );
        run[++last] = right;
    }
    int[] t = a; a = b; b = t;
    int o = ao; ao = bo; bo = o;
}
技術不分領域,思想一脈相承,歡迎訪問 橙味菌的博客
相關文章
相關標籤/搜索