演算法學習?挑戰高薪的必經之路!讓面試官滿意的排序演算法(圖文解析)
讓面試官滿意的排序演算法(圖文解析)
-
這種排序演算法能夠讓面試官面露微笑
-
這種排序演算法集各排序演算法之大成
-
這種排序演算法邏輯性十足
-
這種排序演算法能夠展示自己對Java底層的瞭解
這種排序演算法出自Vladimir Yaroslavskiy、Jon Bentley和Josh Bloch三位大牛之手,它就是JDK的排序演算法——java.util.DualPivotQuicksort(雙支點快排)
覺得文章枯燥的朋友,可以看影片學習,免費領取vx【xx13414521】
DualPivotQuicksort
先看一副邏輯圖(如有錯誤請大牛在評論區指正)
插排指的是改進版插排—— 哨兵插排
快排指的是改進版快排—— 雙支點快排
DualPivotQuickSort沒有Object陣列排序的邏輯,此邏輯在Arrays中,好像是歸併+Tim排序
影像應該很清楚:對於不同的資料型別,Java有不同的排序策略:
-
byte、short、char 他們的取值範圍有限,使用計數排序佔用的空間也不過256/65536個單位,只要排序的數量不是特別少(有一個計數排序閾值,低於這個閾值的話就沒有不要用空間換時間了),都應使用計數排序
-
int、long、float、double 他們的取值範圍非常的大,不適合使用計數排序
-
float和double他們又有特殊情況:
- 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為排序數值可能取值的數量),只有在範圍較小的時候才應該考慮計數排序
(原始碼以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的大牛顯然考慮了這一點:他們在歸併排序之前對元素進行了是否能穩定快排的判斷:
- 如果陣列本身幾乎已經排好了(可以看出幾段有序陣列的拼接),那還排什麼,理一理返回就行了
- 如果出現連續33個相等元素——使用快排(實話說,我沒弄明白為什麼,有無大牛給我指點迷津?)
//判斷結構是否適合歸併排序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; }
最後
第一次看文章的朋友可以關注我
Android進階之路
不定期釋出大廠面試題、Android架構技術知識點及解析等內容,還有學習PDF+原始碼筆記+面試文件+進階影片分享
點選就看
學習小彩蛋
點個贊,收藏起來認真學習哦
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69952849/viewspace-2672205/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- 演算法學習之路|快速排序演算法排序
- 小白機器學習基礎演算法學習必經之路(下)機器學習演算法
- 這次讓面試官非常滿意:手撕深拷貝[15行]面試
- 排序學習 - 為了面對演算法面試(1)排序演算法面試
- 演算法學習之路|划拳演算法
- 演算法學習之路|二分圖的最大匹配—匈牙利演算法(Dfs實現)演算法
- 演算法學習 - 基礎排序演算法演算法排序
- 挑戰高薪!學習人工智慧,你準備好了嗎?高薪人工智慧
- 排序演算法解析排序演算法
- 演算法學習之路|A除以B演算法
- 演算法學習之路|列印排名演算法
- 演算法學習之路|方格分割演算法
- 演算法學習之路|朋友數演算法
- 演算法學習之路|SpellItRight演算法
- 演算法學習之路|歐幾里得遊戲演算法遊戲
- 演算法學習之路|月餅演算法
- 演算法學習之路|PATRanking演算法
- 演算法學習之路|列印沙漏演算法
- 演算法學習之路|結繩演算法
- 演算法學習之路|數零壹演算法
- 如何解釋vue的生命週期才能令面試官滿意?Vue面試
- 演算法學習 – 歸併排序演算法排序
- 演算法學習 - 歸併排序演算法排序
- 演算法學習-遞迴排序演算法遞迴排序
- IOS中學習排序演算法iOS排序演算法
- 關於前端中常用的排序演算法-圖文講解前端排序演算法
- 這樣回答繼承,面試官可能更滿意繼承面試
- 面試中的排序演算法總結面試排序演算法
- 圖文並茂排序與演算法總結排序演算法
- 演算法學習之路|開學寄語演算法
- 幾種經典的排序演算法排序演算法
- 排序演算法(七大經典排序演算法)排序演算法
- 十大經典排序演算法動畫與解析排序演算法動畫
- 演算法學習之路|說反話演算法
- 演算法學習之路|幼兒園買玩具演算法
- 演算法學習之路|小賭怡情演算法
- 演算法學習之路|影像過濾演算法
- 演算法學習之路|日期問題演算法