您好,登錄后才能下訂單哦!
這種排序算法能夠讓面試官面露微笑
這種排序算法集各排序算法之大成
這種排序算法邏輯性十足
這種排序算法能夠展示自己對Java底層的了解
這種排序算法出自Vladimir Yaroslavskiy、Jon Bentley和Josh Bloch三位大牛之手,它就是JDK的排序算法——java.util.DualPivotQuicksort(雙支點快排)
想看以往學習內容的朋友
可以看我的GitHub: https://github.com/Meng997998/AndroidJX
先看一副邏輯圖(如有錯誤請大牛在評論區指正)
插排指的是改進版插排—— 哨兵插排
快排指的是改進版快排—— 雙支點快排
DualPivotQuickSort沒有Object數組排序的邏輯,此邏輯在Arrays中,好像是歸并+Tim排序
圖像應該很清楚:對于不同的數據類型,Java有不同的排序策略:
byte、short、char 他們的取值范圍有限,使用計數排序占用的空間也不過256/65536個單位,只要排序的數量不是特別少(有一個計數排序閾值,低于這個閾值的話就沒有不要用空間換時間了),都應使用計數排序
int、long、float、double 他們的取值范圍非常的大,不適合使用計數排序
float和double他們又有特殊情況:
Object
計數排序是以空間換時間的排序算法,它時間復雜度O(n),空間復雜度O(m)(m為排序數值可能取值的數量),只有在范圍較小的時候才應該考慮計數排序
(源碼以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)其實相差無幾,而插排的空間占用率要少于快排和歸并排序,因而當數組元素較少時(<插排閾值),優先使用插排
哨兵插排是對插排的優化,原插排每次取一個值進行遍歷插入,而哨兵插排則取兩個,較大的一個(小端在前的排序)作為哨兵,當哨兵遍歷到自己的位置時,另一個值可以直接從哨兵當前位置開始遍歷,而不用再重頭遍歷
只畫了靜態圖,如果有好的繪制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;
重頭戲:雙支點快排!
快排雖然穩定性不如歸并排序,但是它不用復制來復制去,省去了一段數組的空間,在數組元素較少的情況下穩定性影響也會下降(>插排閾值 ,<快排閾值),優先使用快排
雙支點快排在原有的快排基礎上,多加一個支點,左右共進,效率提升
看圖:
第一步,取支點
注意:如果5個節點有相等的任兩個節點,說明數據不夠均勻,那就要使用單節點快排
快排
源碼(int為例,這么長估計也沒人看)
// Inexpensive approximation of length / 7 // 快排閾值是286 其7分之一小于等于1/8+1/64+1int seventh = (length >> 3) + (length >> 6) + 1;// 獲取分成7份的五個中間點int e3 = (left + right) >>> 1; // The midpointint 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; } } } }// Pointersint less = left; // The index of the first element of center partint 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的大牛顯然考慮了這一點:他們在歸并排序之前對元素進行了是否能穩定快排的判斷:
//判斷結構是否適合歸并排序int[] run = new int[MAX_RUN_COUNT + 1];int count = 0; run[0] = left;// Check if the array is nearly sortedfor (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 mergingint[] b; // temp array; alternates with aint ao, bo; // array offsets from 'left'int blen = right - left; // space needed for bif (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; }// Mergingfor (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; }
點擊就看
學習小彩蛋
點個贊,收藏起來認真學習哦
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。