Dart語(yǔ)法進(jìn)階篇(一)-- Dart源碼的排序算法詳解

版權(quán)聲明:本文為博主原創(chuàng)文章,未經(jīng)博主允許不得轉(zhuǎn)載。http://www.reibang.com/p/44ae73a58ebc
轉(zhuǎn)載請(qǐng)標(biāo)明出處:
http://www.reibang.com/p/44ae73a58ebc
本文出自 AWeiLoveAndroid的博客


Flutter系列博文鏈接 ↓:

工具安裝:

Flutter基礎(chǔ)篇:

Flutter進(jìn)階篇:

Dart語(yǔ)法系列博文鏈接 ↓:

Dart語(yǔ)法基礎(chǔ)篇:

Dart語(yǔ)法進(jìn)階篇:


我在搜索print源碼的時(shí)候谒获,發(fā)現(xiàn)了print屬于part of dart._internal;蛤肌,然后我繼續(xù)點(diǎn)進(jìn)去發(fā)現(xiàn)part 'sort.dart';,看名字我大概猜到了這是一個(gè)用于排序的算法類批狱。點(diǎn)進(jìn)去一看裸准,果然是這樣的。代碼總共380多行赔硫,不是很多炒俱,但是很簡(jiǎn)潔。其中就用到了插入排序算法和雙向快速排序算法爪膊。

首先來(lái)看看這個(gè)類的結(jié)構(gòu):

// Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

part of dart._internal;

/**
 * Dual-Pivot Quicksort algorithm.
 *
 * This class implements the dual-pivot quicksort algorithm as presented in
 * Vladimir Yaroslavskiy's paper.
 *
 * Some improvements have been copied from Android's implementation.
 */
class Sort {
  // When a list has less then [:_INSERTION_SORT_THRESHOLD:] elements it will
  // be sorted by an insertion sort.
  static const int _INSERTION_SORT_THRESHOLD = 32;

  /**
   * Sorts all elements of the given list [:a:] according to the given
   * [:compare:] function.
   *
   * The [:compare:] function takes two arguments [:x:] and [:y:] and returns
   *  -1 if [:x < y:],
   *   0 if [:x == y:], and
   *   1 if [:x > y:].
   *
   * The function's behavior must be consistent. It must not return different
   * results for the same values.
   */
  static void sort<E>(List<E> a, int compare(E a, E b)) {
    _doSort(a, 0, a.length - 1, compare);
  }

  /**
   * Sorts all elements in the range [:from:] (inclusive) to [:to:] (exclusive)
   * of the given list [:a:].
   *
   * If the given range is invalid an "OutOfRange" error is raised.
   * TODO(floitsch): do we want an error?
   *
   * See [:sort:] for requirements of the [:compare:] function.
   */
  static void sortRange<E>(List<E> a, int from, int to, int compare(E a, E b)) {
    if ((from < 0) || (to > a.length) || (to < from)) {
      throw "OutOfRange";
    }
    _doSort(a, from, to - 1, compare);
  }

  /**
   * Sorts the list in the interval [:left:] to [:right:] (both inclusive).
   */
  static void _doSort<E>(
      List<E> a, int left, int right, int compare(E a, E b)) {
    if ((right - left) <= _INSERTION_SORT_THRESHOLD) {
      _insertionSort(a, left, right, compare);
    } else {
      _dualPivotQuicksort(a, left, right, compare);
    }
  }

  static void _insertionSort<E>(
      List<E> a, int left, int right, int compare(E a, E b)) {
    for (int i = left + 1; i <= right; i++) {
      var el = a[i];
      int j = i;
      while ((j > left) && (compare(a[j - 1], el) > 0)) {
        a[j] = a[j - 1];
        j--;
      }
      a[j] = el;
    }
  }

  static void _dualPivotQuicksort<E>(
      List<E> a, int left, int right, int compare(E a, E b)) {
    assert(right - left > _INSERTION_SORT_THRESHOLD);

    // Compute the two pivots by looking at 5 elements.
    int sixth = (right - left + 1) ~/ 6;
    int index1 = left + sixth;
    int index5 = right - sixth;
    int index3 = (left + right) ~/ 2; // The midpoint.
    int index2 = index3 - sixth;
    int index4 = index3 + sixth;

    var el1 = a[index1];
    var el2 = a[index2];
    var el3 = a[index3];
    var el4 = a[index4];
    var el5 = a[index5];

    // Sort the selected 5 elements using a sorting network.
    if (compare(el1, el2) > 0) {
      var t = el1;
      el1 = el2;
      el2 = t;
    }
    if (compare(el4, el5) > 0) {
      var t = el4;
      el4 = el5;
      el5 = t;
    }
    if (compare(el1, el3) > 0) {
      var t = el1;
      el1 = el3;
      el3 = t;
    }
    if (compare(el2, el3) > 0) {
      var t = el2;
      el2 = el3;
      el3 = t;
    }
    if (compare(el1, el4) > 0) {
      var t = el1;
      el1 = el4;
      el4 = t;
    }
    if (compare(el3, el4) > 0) {
      var t = el3;
      el3 = el4;
      el4 = t;
    }
    if (compare(el2, el5) > 0) {
      var t = el2;
      el2 = el5;
      el5 = t;
    }
    if (compare(el2, el3) > 0) {
      var t = el2;
      el2 = el3;
      el3 = t;
    }
    if (compare(el4, el5) > 0) {
      var t = el4;
      el4 = el5;
      el5 = t;
    }

    var pivot1 = el2;
    var pivot2 = el4;

    // el2 and el4 have been saved in the pivot variables. They will be written
    // back, once the partitioning is finished.
    a[index1] = el1;
    a[index3] = el3;
    a[index5] = el5;

    a[index2] = a[left];
    a[index4] = a[right];

    int less = left + 1; // First element in the middle partition.
    int great = right - 1; // Last element in the middle partition.

    bool pivots_are_equal = (compare(pivot1, pivot2) == 0);
    if (pivots_are_equal) {
      var pivot = pivot1;
      // Degenerated case where the partitioning becomes a Dutch national flag
      // problem.
      //
      // [ |  < pivot  | == pivot | unpartitioned | > pivot  | ]
      //  ^             ^          ^             ^            ^
      // left         less         k           great         right
      //
      // a[left] and a[right] are undefined and are filled after the
      // partitioning.
      //
      // Invariants:
      //   1) for x in ]left, less[ : x < pivot.
      //   2) for x in [less, k[ : x == pivot.
      //   3) for x in ]great, right[ : x > pivot.
      for (int k = less; k <= great; k++) {
        var ak = a[k];
        int comp = compare(ak, pivot);
        if (comp == 0) continue;
        if (comp < 0) {
          if (k != less) {
            a[k] = a[less];
            a[less] = ak;
          }
          less++;
        } else {
          // comp > 0.
          //
          // Find the first element <= pivot in the range [k - 1, great] and
          // put [:ak:] there. We know that such an element must exist:
          // When k == less, then el3 (which is equal to pivot) lies in the
          // interval. Otherwise a[k - 1] == pivot and the search stops at k-1.
          // Note that in the latter case invariant 2 will be violated for a
          // short amount of time. The invariant will be restored when the
          // pivots are put into their final positions.
          while (true) {
            comp = compare(a[great], pivot);
            if (comp > 0) {
              great--;
              // This is the only location in the while-loop where a new
              // iteration is started.
              continue;
            } else if (comp < 0) {
              // Triple exchange.
              a[k] = a[less];
              a[less++] = a[great];
              a[great--] = ak;
              break;
            } else {
              // comp == 0;
              a[k] = a[great];
              a[great--] = ak;
              // Note: if great < k then we will exit the outer loop and fix
              // invariant 2 (which we just violated).
              break;
            }
          }
        }
      }
    } else {
      // We partition the list into three parts:
      //  1. < pivot1
      //  2. >= pivot1 && <= pivot2
      //  3. > pivot2
      //
      // During the loop we have:
      // [ | < pivot1 | >= pivot1 && <= pivot2 | unpartitioned  | > pivot2  | ]
      //  ^            ^                        ^              ^             ^
      // left         less                     k              great        right
      //
      // a[left] and a[right] are undefined and are filled after the
      // partitioning.
      //
      // Invariants:
      //   1. for x in ]left, less[ : x < pivot1
      //   2. for x in [less, k[ : pivot1 <= x && x <= pivot2
      //   3. for x in ]great, right[ : x > pivot2
      for (int k = less; k <= great; k++) {
        var ak = a[k];
        int comp_pivot1 = compare(ak, pivot1);
        if (comp_pivot1 < 0) {
          if (k != less) {
            a[k] = a[less];
            a[less] = ak;
          }
          less++;
        } else {
          int comp_pivot2 = compare(ak, pivot2);
          if (comp_pivot2 > 0) {
            while (true) {
              int comp = compare(a[great], pivot2);
              if (comp > 0) {
                great--;
                if (great < k) break;
                // This is the only location inside the loop where a new
                // iteration is started.
                continue;
              } else {
                // a[great] <= pivot2.
                comp = compare(a[great], pivot1);
                if (comp < 0) {
                  // Triple exchange.
                  a[k] = a[less];
                  a[less++] = a[great];
                  a[great--] = ak;
                } else {
                  // a[great] >= pivot1.
                  a[k] = a[great];
                  a[great--] = ak;
                }
                break;
              }
            }
          }
        }
      }
    }

    // Move pivots into their final positions.
    // We shrunk the list from both sides (a[left] and a[right] have
    // meaningless values in them) and now we move elements from the first
    // and third partition into these locations so that we can store the
    // pivots.
    a[left] = a[less - 1];
    a[less - 1] = pivot1;
    a[right] = a[great + 1];
    a[great + 1] = pivot2;

    // The list is now partitioned into three partitions:
    // [ < pivot1   | >= pivot1 && <= pivot2   |  > pivot2   ]
    //  ^            ^                        ^             ^
    // left         less                     great        right

    // Recursive descent. (Don't include the pivot values.)
    _doSort(a, left, less - 2, compare);
    _doSort(a, great + 2, right, compare);

    if (pivots_are_equal) {
      // All elements in the second partition are equal to the pivot. No
      // need to sort them.
      return;
    }

    // In theory it should be enough to call _doSort recursively on the second
    // partition.
    // The Android source however removes the pivot elements from the recursive
    // call if the second partition is too large (more than 2/3 of the list).
    if (less < index1 && great > index5) {
      while (compare(a[less], pivot1) == 0) {
        less++;
      }
      while (compare(a[great], pivot2) == 0) {
        great--;
      }

      // Copy paste of the previous 3-way partitioning with adaptions.
      //
      // We partition the list into three parts:
      //  1. == pivot1
      //  2. > pivot1 && < pivot2
      //  3. == pivot2
      //
      // During the loop we have:
      // [ == pivot1 | > pivot1 && < pivot2 | unpartitioned  | == pivot2 ]
      //              ^                      ^              ^
      //            less                     k              great
      //
      // Invariants:
      //   1. for x in [ *, less[ : x == pivot1
      //   2. for x in [less, k[ : pivot1 < x && x < pivot2
      //   3. for x in ]great, * ] : x == pivot2
      for (int k = less; k <= great; k++) {
        var ak = a[k];
        int comp_pivot1 = compare(ak, pivot1);
        if (comp_pivot1 == 0) {
          if (k != less) {
            a[k] = a[less];
            a[less] = ak;
          }
          less++;
        } else {
          int comp_pivot2 = compare(ak, pivot2);
          if (comp_pivot2 == 0) {
            while (true) {
              int comp = compare(a[great], pivot2);
              if (comp == 0) {
                great--;
                if (great < k) break;
                // This is the only location inside the loop where a new
                // iteration is started.
                continue;
              } else {
                // a[great] < pivot2.
                comp = compare(a[great], pivot1);
                if (comp < 0) {
                  // Triple exchange.
                  a[k] = a[less];
                  a[less++] = a[great];
                  a[great--] = ak;
                } else {
                  // a[great] == pivot1.
                  a[k] = a[great];
                  a[great--] = ak;
                }
                break;
              }
            }
          }
        }
      }
      // The second partition has now been cleared of pivot elements and looks
      // as follows:
      // [  *  |  > pivot1 && < pivot2  | * ]
      //        ^                      ^
      //       less                  great
      // Sort the second partition using recursive descent.
      _doSort(a, less, great, compare);
    } else {
      // The second partition looks as follows:
      // [  *  |  >= pivot1 && <= pivot2  | * ]
      //        ^                        ^
      //       less                    great
      // Simply sort it by recursive descent.
      _doSort(a, less, great, compare);
    }
  }
}
還有 1% 的精彩內(nèi)容
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
支付 ¥5.00 繼續(xù)閱讀
  • 序言:七十年代末权悟,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子推盛,更是在濱河造成了極大的恐慌峦阁,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件耘成,死亡現(xiàn)場(chǎng)離奇詭異榔昔,居然都是意外死亡驹闰,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門撒会,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)嘹朗,“玉大人,你說(shuō)我怎么就攤上這事茧彤÷庀裕” “怎么了?”我有些...
    開(kāi)封第一講書人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵曾掂,是天一觀的道長(zhǎng)惫谤。 經(jīng)常有香客問(wèn)我,道長(zhǎng)珠洗,這世上最難降的妖魔是什么溜歪? 我笑而不...
    開(kāi)封第一講書人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮许蓖,結(jié)果婚禮上蝴猪,老公的妹妹穿的比我還像新娘。我一直安慰自己膊爪,他們只是感情好自阱,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著米酬,像睡著了一般沛豌。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上赃额,一...
    開(kāi)封第一講書人閱讀 51,754評(píng)論 1 307
  • 那天加派,我揣著相機(jī)與錄音,去河邊找鬼跳芳。 笑死芍锦,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的飞盆。 我是一名探鬼主播娄琉,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼桨啃!你這毒婦竟也來(lái)了车胡?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤照瘾,失蹤者是張志新(化名)和其女友劉穎匈棘,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體析命,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡主卫,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年逃默,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片簇搅。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡完域,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出瘩将,到底是詐尸還是另有隱情吟税,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布姿现,位于F島的核電站肠仪,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏备典。R本人自食惡果不足惜异旧,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望提佣。 院中可真熱鬧吮蛹,春花似錦、人聲如沸拌屏。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)倚喂。三九已至然低,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間务唐,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工带兜, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留枫笛,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓刚照,卻偏偏與公主長(zhǎng)得像刑巧,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子无畔,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容