[关闭]
@lzb1096101803 2016-03-18T15:56:46.000000Z 字数 11297 阅读 481

JDK7中的排序算法(快排)

电话面试


http://www.tuicool.com/articles/BfY7Nz
Collections.sort和Arrays.sort

在JDK7 中新增了java.util.DualPivotQuicksort这个类,里面实现于2009年发表的Dual-Pivot Quicksort 算法。其主要的设计是改进了Quicksort算法。使之效率大幅提高。为些Collections.sort(),Arrays.sort()等的实现部分(现在主要是原始类型数据,其它类型应当在测试开发中,根据其注释将来会改)使用了这个类。通过对比JDK7与JDK5的Arrays类发现JDK7中做了非常大的改变。看来以前SUN对算法的重视程度还真的不及做DB出生的Oracle,快速排序法在1960年就表达,但并没有在JDK中实现。

DualPivotQuicksort

一般的快速排序采用一个枢轴来把一个数组划分成两半,然后递归之。

大量经验数据表面,采用两个枢轴来划分成3份的算法更高效,这就是DualPivotQuicksort。

算法思想:
选出两个枢轴P1和P2,需要3个指针L,K,G。
3个指针的作用如下图:

算法为以下的步骤:

1、小于27的数组,使用插入排序(或47)。
2、选择枢轴P1和P2。(假设使用数组头和尾)。
3、P1需要小于P2,否者交换。
现在数组被分成4份,left到L的小于P1的数,L到K的大于P1小于P2的数,G到rigth的大于P2的数,待处理的K到G的中间的数(逐步被处理到前3个区域中)
4、L从开始初始化直至不小于P1,K初始化为L-1,G从结尾初始化直至不大于P2。K是主移动的指针,来一步一步吞噬中间区域。
**当大于P1小于P2,K++。
**
当小于P1,交换L和K的数,L++,K++。
****当大于P2,如果G的数小于P1,把L上的数放在K上,把G的数放在L上,L++,再把K以前的数放在G上,G--,K++,完成一次L,K,G的互相交换。否则交换K和G,并G--,K++。
5、递归4。
6、交换P1到L-1上。交换P2到G+1上。
7、递归之。

JDK源码

流程图

TimSort

直接调用的sort第一级:

  1. public static void sort(int[] a, int left, int right) {
  2. // Use Quicksort on small arrays
  3. if (right - left < QUICKSORT_THRESHOLD) {//门限为286
  4. sort(a, left, right, true);
  5. return;
  6. }
  7. /*
  8. * Index run[i] is the start of i-th run
  9. * (ascending or descending sequence).
  10. */
  11. int[] run = new int[MAX_RUN_COUNT + 1];
  12. int count = 0; run[0] = left;
  13. // Check if the array is nearly sorted
  14. for (int k = left; k < right; run[count] = k) {
  15. if (a[k] < a[k + 1]) { // ascending
  16. while (++k <= right && a[k - 1] <= a[k]);
  17. } else if (a[k] > a[k + 1]) { // descending
  18. while (++k <= right && a[k - 1] >= a[k]);
  19. for (int lo = run[count] - 1, hi = k; ++lo < --hi; ) {
  20. int t = a[lo]; a[lo] = a[hi]; a[hi] = t;
  21. }
  22. } else { // equal
  23. for (int m = MAX_RUN_LENGTH; ++k <= right && a[k - 1] == a[k]; ) {
  24. if (--m == 0) {
  25. sort(a, left, right, true);
  26. return;
  27. }
  28. }
  29. }
  30. /*
  31. * The array is not highly structured,
  32. * use Quicksort instead of merge sort.
  33. */
  34. if (++count == MAX_RUN_COUNT) {
  35. sort(a, left, right, true);
  36. return;
  37. }
  38. }
  39. // Check special cases
  40. if (run[count] == right++) { // The last run contains one element
  41. run[++count] = right;
  42. } else if (count == 1) { // The array is already sorted
  43. return;
  44. }
  45. /*
  46. * Create temporary array, which is used for merging.
  47. * Implementation note: variable "right" is increased by 1.
  48. */
  49. int[] b; byte odd = 0;
  50. for (int n = 1; (n <<= 1) < count; odd ^= 1);
  51. if (odd == 0) {
  52. b = a; a = new int[b.length];
  53. for (int i = left - 1; ++i < right; a[i] = b[i]);
  54. } else {
  55. b = new int[a.length];
  56. }
  57. // Merging
  58. for (int last; count > 1; count = last) {
  59. for (int k = (last = 0) + 2; k <= count; k += 2) {
  60. int hi = run[k], mi = run[k - 1];
  61. for (int i = run[k - 2], p = i, q = mi; i < hi; ++i) {
  62. if (q >= hi || p < mi && a[p] <= a[q]) {
  63. b[i] = a[p++];
  64. } else {
  65. b[i] = a[q++];
  66. }
  67. }
  68. run[++last] = hi;
  69. }
  70. if ((count & 1) != 0) {
  71. for (int i = right, lo = run[count - 1]; --i >= lo;
  72. b[i] = a[i]
  73. );
  74. run[++last] = right;
  75. }
  76. int[] t = a; a = b; b = t;
  77. }
  78. }

1、当小于286时,直接使用双枢轴快速排序。
2、大于286时,先使用TimSort的思想,找出正序或者倒序的数(run的栈),然后合并各个run,最后完成TimSort。
3、在找出run的时候,找出的run个数大于67时,即认为它是一个比较乱序的数组,就直接采用双枢轴快速排序。

双元素插入排序

下面看看双枢轴快速排序的实现(代码太长,分解之):

  1. /**
  2. * Sorts the specified range of the array by Dual-Pivot Quicksort.
  3. *
  4. * @param a the array to be sorted
  5. * @param left the index of the first element, inclusive, to be sorted
  6. * @param right the index of the last element, inclusive, to be sorted
  7. * @param leftmost indicates if this part is the leftmost in the range
  8. */
  9. private static void sort(int[] a, int left, int right, boolean leftmost) {
  10. int length = right - left + 1;
  11. // Use insertion sort on tiny arrays
  12. if (length < INSERTION_SORT_THRESHOLD) {//47个
  13. if (leftmost) {
  14. /*
  15. * Traditional (without sentinel) insertion sort,
  16. * optimized for server VM, is used in case of
  17. * the leftmost part.
  18. */
  19. for (int i = left, j = i; i < right; j = ++i) {
  20. int ai = a[i + 1];
  21. while (ai < a[j]) {
  22. a[j + 1] = a[j];
  23. if (j-- == left) {
  24. break;
  25. }
  26. }
  27. a[j + 1] = ai;
  28. }
  29. } else {
  30. /*
  31. * Skip the longest ascending sequence.
  32. */
  33. do {
  34. if (left >= right) {
  35. return;
  36. }
  37. } while (a[++left] >= a[left - 1]);
  38. /*
  39. * Every element from adjoining part plays the role
  40. * of sentinel, therefore this allows us to avoid the
  41. * left range check on each iteration. Moreover, we use
  42. * the more optimized algorithm, so called pair insertion
  43. * sort, which is faster (in the context of Quicksort)
  44. * than traditional implementation of insertion sort.
  45. */
  46. for (int k = left; ++left <= right; k = ++left) {
  47. int a1 = a[k], a2 = a[left];
  48. if (a1 < a2) {
  49. a2 = a1; a1 = a[left];
  50. }
  51. while (a1 < a[--k]) {
  52. a[k + 2] = a[k];
  53. }
  54. a[++k + 1] = a1;
  55. while (a2 < a[--k]) {
  56. a[k + 1] = a[k];
  57. }
  58. a[k + 1] = a2;
  59. }
  60. int last = a[right];
  61. while (last < a[--right]) {
  62. a[right + 1] = a[right];
  63. }
  64. a[right + 1] = last;
  65. }
  66. return;
  67. }

当小于47个时,使用插入排序。

参数a为需要排序的数组,left代表需要排序的数组区间中最左边元素的索引,right代表区间中最右边元素的索引,leftmost代表该区间是否是数组中最左边的区间。举个例子:
数组:[2, 4, 8, 5, 6, 3, 0, -3, 9]可以分成三个区间(2, 4, 8){5, 6}<3, 0, -3, 9>
对于()区间,left=0, right=2, leftmost=true
对于 {}区间, left=3, right=4, leftmost=false,同理可得<>区间的相应参数
当区间长度小于47时,该方法会采用插入排序;否则采用快速排序。
1、 当leftmost为true时,它会采用传统的插入排序(traditional insertion sort),代码也较简单,其过程类似打牌时抓牌插牌。
2、 当leftmost为false时,它采用一种新型的插入排序(pair insertion sort),改进之处在于每次遍历前面已排好序的数组需要 插入两个元素 ,而传统插入排序在遍历过程中只需要为一个元素找到合适的位置插入。对于插入排序来讲,其关键在于为待插入元素找到合适的插入位置,为了找到这个位置,需要遍历之前已经排好序的子数组,所以对于插入排序来讲,整个排序过程中其遍历的元素个数决定了它的性能。很显然, 每次遍历插入两个元素可以减少排序过程中遍历的元素个数

为左边区间时,pair insertion sort在左边元素比较大时,会越界。

双枢轴快速排序

对于快速排序来讲,其每一次递归所做的是使需要排序的子区间变得 更加有序 ,而不是绝对有序;所以对于快速排序来说,其性能决定于每次递归操作使待排序子区间变得有序的程度,另一个决定因素当然就是递归次数。快速排序使子区间变得相对有序的关键是pivot,所以我们优化的方向也应该在于pivot,那就增加pivot的个数吧,而且我们可以发现,增加pivot的个数,对递归次数并不会有太大影响,有时甚至可以使递归次数减少。和insert sort类似的问题就是,pivot增加为几个呢?很显然,pivot的值也不能太大;记住,任何优化都是 有代价的 ,而增加pivot的代价就隐藏在每次 交换 元素的位置过程中。

下面是寻找枢轴的过程:

  1. // Inexpensive approximation of length / 7,1/7=1/8+1/32
  2. int seventh = (length >> 3) + (length >> 6) + 1;
  3. /*
  4. * Sort five evenly spaced elements around (and including) the
  5. * center element in the range. These elements will be used for
  6. * pivot selection as described below. The choice for spacing
  7. * these elements was empirically determined to work well on
  8. * a wide variety of inputs.
  9. */
  10. int e3 = (left + right) >>> 1; // The midpoint
  11. int e2 = e3 - seventh;
  12. int e1 = e2 - seventh;
  13. int e4 = e3 + seventh;
  14. int e5 = e4 + seventh;
  15. // Sort these elements using insertion sort
  16. if (a[e2] < a[e1]) { int t = a[e2]; a[e2] = a[e1]; a[e1] = t; }
  17. if (a[e3] < a[e2]) { int t = a[e3]; a[e3] = a[e2]; a[e2] = t;
  18. if (t < a[e1]) { a[e2] = a[e1]; a[e1] = t; }
  19. }
  20. if (a[e4] < a[e3]) { int t = a[e4]; a[e4] = a[e3]; a[e3] = t;
  21. if (t < a[e2]) { a[e3] = a[e2]; a[e2] = t;
  22. if (t < a[e1]) { a[e2] = a[e1]; a[e1] = t; }
  23. }
  24. }
  25. if (a[e5] < a[e4]) { int t = a[e5]; a[e5] = a[e4]; a[e4] = t;
  26. if (t < a[e3]) { a[e4] = a[e3]; a[e3] = t;
  27. if (t < a[e2]) { a[e3] = a[e2]; a[e2] = t;
  28. if (t < a[e1]) { a[e2] = a[e1]; a[e1] = t; }
  29. }
  30. }
  31. }
  32. // Pointers
  33. int less = left; // The index of the first element of center part
  34. int great = right; // The index before the first element of right part
  35. if (a[e1] != a[e2] && a[e2] != a[e3] && a[e3] != a[e4] && a[e4] != a[e5]) {
  36. /*
  37. * Use the second and fourth of the five sorted elements as pivots.
  38. * These values are inexpensive approximations of the first and
  39. * second terciles of the array. Note that pivot1 <= pivot2.
  40. */
  41. int pivot1 = a[e2];
  42. int pivot2 = a[e4];
  43. /*
  44. * The first and the last elements to be sorted are moved to the
  45. * locations formerly occupied by the pivots. When partitioning
  46. * is complete, the pivots are swapped back into their final
  47. * positions, and excluded from subsequent sorting.
  48. */
  49. a[e2] = a[left];
  50. a[e4] = a[right];
  1. pivot的选取方式是将数组分成近视等长的七段,而这七段其实是被5个元素分开的,将这5个元素从小到大排序,取出第2个和第4个,分别作为pivot1和pivot2。

注意:当这个5元素都互不相等时,才采用双枢轴快速排序!
2. Pivot选取完之后,分别从左右两端向中间遍历,左边遍历停止的条件是遇到一个大于等于pivot1的值,并把那个位置标记为less;右边遍历的停止条件是遇到一个小于等于pivot2的值,并把那个位置标记为great
3. 然后从less位置向后遍历,遍历的位置用k表示,会遇到以下几种情况:
a. k位置的值比pivot1小,那就交换k位置和less位置的值,并是less的值加1;这样就使得less位置左边的值都小于pivot1,而less位置和k位置之间的值大于等于pivot1
b. k位置的值大于pivot2,那就从great位置向左遍历,遍历停止条件是遇到一个小于等于pivot2的值,假如这个值小于pivot1,就把这个值写到less位置,把less位置的值写道k位置,把k位置的值写道great位置,最后less++,great--;加入这个值大于等于pivot1,就交换k位置和great位置,之后great--。
4. 完成上述过程之后,带排序的子区间就被分成了三段(pivot2),最后分别对这三段采用递归就行了。

  1. /*
  2. * Skip elements, which are less or greater than pivot values.
  3. */
  4. while (a[++less] < pivot1);
  5. while (a[--great] > pivot2);
  6. /*
  7. * Partitioning:
  8. *
  9. * left part center part right part
  10. * +--------------------------------------------------------------+
  11. * | < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 |
  12. * +--------------------------------------------------------------+
  13. * ^ ^ ^
  14. * | | |
  15. * less k great
  16. *
  17. * Invariants:
  18. *
  19. * all in (left, less) < pivot1
  20. * pivot1 <= all in [less, k) <= pivot2
  21. * all in (great, right) > pivot2
  22. *
  23. * Pointer k is the first index of ?-part.
  24. */
  25. outer:
  26. for (int k = less - 1; ++k <= great; ) {
  27. int ak = a[k];
  28. if (ak < pivot1) { // Move a[k] to left part
  29. a[k] = a[less];
  30. /*
  31. * Here and below we use "a[i] = b; i++;" instead
  32. * of "a[i++] = b;" due to performance issue.
  33. */
  34. a[less] = ak;
  35. ++less;
  36. } else if (ak > pivot2) { // Move a[k] to right part
  37. while (a[great] > pivot2) {
  38. if (great-- == k) {
  39. break outer;
  40. }
  41. }
  42. if (a[great] < pivot1) { // a[great] <= pivot2
  43. a[k] = a[less];
  44. a[less] = a[great];
  45. ++less;
  46. } else { // pivot1 <= a[great] <= pivot2
  47. a[k] = a[great];
  48. }
  49. /*
  50. * Here and below we use "a[i] = b; i--;" instead
  51. * of "a[i--] = b;" due to performance issue.
  52. */
  53. a[great] = ak;
  54. --great;
  55. }
  56. }
  57. // Swap pivots into their final positions
  58. a[left] = a[less - 1]; a[less - 1] = pivot1;
  59. a[right] = a[great + 1]; a[great + 1] = pivot2;
  60. // Sort left and right parts recursively, excluding known pivots
  61. sort(a, left, less - 2, leftmost);
  62. sort(a, great + 2, right, false);
  63. 上述的代码不包含递归中间的数,当中间的数过于多时,会作出下面举动:
  64. /*
  65. * If center part is too large (comprises > 4/7 of the array),
  66. * swap internal pivot values to ends.
  67. */
  68. if (less < e1 && e5 < great) {
  69. /*
  70. * Skip elements, which are equal to pivot values.
  71. */
  72. while (a[less] == pivot1) {
  73. ++less;
  74. }
  75. while (a[great] == pivot2) {
  76. --great;
  77. }
  78. /*
  79. * Partitioning:
  80. *
  81. * left part center part right part
  82. * +----------------------------------------------------------+
  83. * | == pivot1 | pivot1 < && < pivot2 | ? | == pivot2 |
  84. * +----------------------------------------------------------+
  85. * ^ ^ ^
  86. * | | |
  87. * less k great
  88. *
  89. * Invariants:
  90. *
  91. * all in (*, less) == pivot1
  92. * pivot1 < all in [less, k) < pivot2
  93. * all in (great, *) == pivot2
  94. *
  95. * Pointer k is the first index of ?-part.
  96. */
  97. outer:
  98. for (int k = less - 1; ++k <= great; ) {
  99. int ak = a[k];
  100. if (ak == pivot1) { // Move a[k] to left part
  101. a[k] = a[less];
  102. a[less] = ak;
  103. ++less;
  104. } else if (ak == pivot2) { // Move a[k] to right part
  105. while (a[great] == pivot2) {
  106. if (great-- == k) {
  107. break outer;
  108. }
  109. }
  110. if (a[great] == pivot1) { // a[great] < pivot2
  111. a[k] = a[less];
  112. /*
  113. * Even though a[great] equals to pivot1, the
  114. * assignment a[less] = pivot1 may be incorrect,
  115. * if a[great] and pivot1 are floating-point zeros
  116. * of different signs. Therefore in float and
  117. * double sorting methods we have to use more
  118. * accurate assignment a[less] = a[great].
  119. */
  120. a[less] = pivot1;
  121. ++less;
  122. } else { // pivot1 < a[great] < pivot2
  123. a[k] = a[great];
  124. }
  125. a[great] = ak;
  126. --great;
  127. }
  128. }
  129. }
  130. // Sort center part recursively
  131. sort(a, less, great, false);

就是当中间的数超过4/7的时候,按照划分应该很平均才对,所以猜想中间的元素有很多等于pivot1和pivot2的数(划分的时候等于的数放在中间),会设法减少中间的数,就是把中间的等于pivot1的数放在前方,把等于pivot的数放在后方。
这个做法类似单枢轴快速排序的时候,作为枢轴的元素也有很多相同的,所以在这个时候,应该跳过这些相同元素来进行快速排序。减少递归。

这个做法就相当于再次划分中间的区域,相当于一共根据两个枢轴划分成了5种(多了两种等于p1和p2的)。对其余3种递归。

单枢轴快速排序

当5个元素有相当的时候,假定现在的情况是数组中有很多相同的元素。

  1. } else { // Partitioning with one pivot
  2. /*
  3. * Use the third of the five sorted elements as pivot.
  4. * This value is inexpensive approximation of the median.
  5. */
  6. int pivot = a[e3];
  7. /*
  8. * Partitioning degenerates to the traditional 3-way
  9. * (or "Dutch National Flag") schema:
  10. *
  11. * left part center part right part
  12. * +-------------------------------------------------+
  13. * | < pivot | == pivot | ? | > pivot |
  14. * +-------------------------------------------------+
  15. * ^ ^ ^
  16. * | | |
  17. * less k great
  18. *
  19. * Invariants:
  20. *
  21. * all in (left, less) < pivot
  22. * all in [less, k) == pivot
  23. * all in (great, right) > pivot
  24. *
  25. * Pointer k is the first index of ?-part.
  26. */
  27. for (int k = less; k <= great; ++k) {
  28. if (a[k] == pivot) {
  29. continue;
  30. }
  31. int ak = a[k];
  32. if (ak < pivot) { // Move a[k] to left part
  33. a[k] = a[less];
  34. a[less] = ak;
  35. ++less;
  36. } else { // a[k] > pivot - Move a[k] to right part
  37. while (a[great] > pivot) {
  38. --great;
  39. }
  40. if (a[great] < pivot) { // a[great] <= pivot
  41. a[k] = a[less];
  42. a[less] = a[great];
  43. ++less;
  44. } else { // a[great] == pivot
  45. /*
  46. * Even though a[great] equals to pivot, the
  47. * assignment a[k] = pivot may be incorrect,
  48. * if a[great] and pivot are floating-point
  49. * zeros of different signs. Therefore in float
  50. * and double sorting methods we have to use
  51. * more accurate assignment a[k] = a[great].
  52. */
  53. a[k] = pivot;
  54. }
  55. a[great] = ak;
  56. --great;
  57. }
  58. }
  59. /*
  60. * Sort left and right parts recursively.
  61. * All elements from center part are equal
  62. * and, therefore, already sorted.
  63. */
  64. sort(a, left, less - 1, leftmost);
  65. sort(a, great + 1, right, false);
  66. }

注意:这是个改进的单枢轴快速排序。这个时候也是3个指针的算法。因为,这个算法就像是分成3类,一类小于枢轴,一类大于枢轴,一类等于枢轴。只用对左右两种进行递归。

TimSort

在Java 6中Arrays.sort()和Collections.sort()使用的是MergeSort,而在Java 7中,内部实现换成了TimSort,其对对象间比较的实现要求更加严格:

  1. Comparator的实现必须保证以下几点(出自这儿):
  2. a). sgn(compare(x, y)) == -sgn(compare(y, x))
  3. b). (compare(x, y)>0) && (compare(y, z)>0) 意味着 compare(x, z)>0
  4. c). compare(x, y)==0 意味着对于任意的zsgn(compare(x, z))==sgn(compare(y, z)) 均成立

而我们的代码中,某个compare()实现片段是这样的:
public int compare(ComparatorTest o1, ComparatorTest o2) {
return o1.getValue() > o2.getValue() ? 1 : -1;
}

这就违背了a)原则:假设X的value为1,Y的value也为1;那么compare(X, Y) ≠ –compare(Y, X)
PS: TimSort不仅内置在各种JDK 7的版本,也存在于Android SDK中(尽管其并没有使用JDK 7)

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注