设为首页收藏本站

IT技术擎 - 最棒的IT web技术交流社区

 找回密码
 注册为IT技术擎人

QQ登录

只需一步,快速开始

搜索
热搜: php h5 jquery
查看: 12|回复: 0

[其他] 学员优秀博文赏析:双基准快速排序实现

[复制链接]

1万

主题

1万

帖子

3万

积分

版主

Rank: 7Rank: 7Rank: 7

积分
35417
发表于 2018-8-10 19:45:25 | 显示全部楼层 |阅读模式
我一般是不会去主动碰算法问题的。上学的时候一个算法复杂度就把我搞烦了,还想让我去搞算法本身?我是这么安慰自己的:反正写CRUD又不需要算法,这辈子都不需要算法的。好吧,其实我是一直不肯承认,不去动算法的原因只有三个字:因为笨!
所以你去看,一般招算法工程师的都是大厂,而且,薪水永远稳居程序员工资的顶端位置。流传在开发界的鄙视链中,算法工程师一直稳居金字塔顶端,俯睨众生。 故,当学员之中出现第一篇涉足算法,还写的有模有样的的博客的时候,我是有点吃惊的。虽然只是基础算法,但这篇博客中除了涉及到了算法本身,还涉及到了源码分析,同时为了保证论证的完整性,文末还给出了reference。 这几乎是一个优秀程序员都会具备的素质,可是我们的这位学员才学习了Java一个月啊~~。直到我看到学员本尊的时候,一切都释然了。你们来感受下他的头像,我可以保证确实是本尊无疑:
隐藏的大侠都应该是如此的。
来,现在我们就来欣赏这位同学的博文,师徒班常同学的《Java中双基准快速排序方法(DualPivotQuicksort.sort())的具体实现》:
====================================================================================================
在Java语言的Arrays类下提供了一系列排序(sort)方法,帮助使用者对各种不同数据类型的数组进行排序. 在1.7之后的版本中, Arrays.sort()方法在操作过程中实际调用的是DualPivotQuicksort类下的sort方法,DualPivotQuicksort和Arrays一样,都在java.util包下,按字面翻译过来,就是双(Dual)基准(Pivot)快速排序(Quicksort)算法.
双基准快速排序算法于2009年由Vladimir Yaroslavskiy提出,是对经典快速排序(Classic Quicksort)进行优化后的一个版本, Java自1.7开始,均使用此方法作为默认排序算法. 接下来,本文就将对此方法的具体实现过程进行简单的介绍.
在正式进入对DualPivotQuicksort的介绍之前,我们先来对经典快速排序的实现思路进行一下简单的了解:
经典快速排序在操作过程中首先会从数组中选取一个基准(Pivot),这个基准可以是数组中的任意一个元素;
随后,将这个数组所有其他元素和Pivot进行比较,比Pivot小的数放在左侧,大的数放在右侧;
如此,我们就在Pivot的左侧和右侧各得到了一个新的数组;
接下来我们再在这两个新的数组中各自选取新的Pivot,把小的放在左侧,大的放在右侧,循环往复,最终就会得到由小到大顺序排列的数组.
下图(via wiki)便是Quicksort的一个具体实现: 在对Quicksort的基本思路有了一定了解之后,下一步我们就来看Java中DualPivotQuicksort.sort是如何实现的;
本方法在实际工作过程中, 并不是对任何传入的数组都直接进行快速排序, 而是会先对数组进行一系列测试, 然后根据数组的具体情况选择最适合的算法来进行排序,下面我们结合源码来看:
首先, 以一个int数组为例,
当一个数组int[] a被传入DualPivotQuicksort.sort()时,该方法还会要求其他一系列参数:
  1. staticvoidsort(int[] a, intleft, intright, int[] work, intworkBase, intworkLen)
复制代码
其中,int[] a是需被排序的int数组, left和right是该数组中需要被排序的部分的左右界限. 而后面的work, workBase和workLen三个参数其实并不会参与双基准快速排序, 而是当系统认为本数组更适合使用归并排序(merge sort)的时候, 供归并排序使用.
但是,在实际使用中,我们并不希望为了排序设置这么多的参数,因此:
Arrays.sort()在调用DualPivotQuicksort.sort()之前,对int数组的排序提供了两种参数列表:
  1. publicstaticvoidsort(int[] a)
复制代码
直接对int[] a 进行排序,以及:
  1. publicstaticvoidsort(int[] a, intfromIndex, inttoIndex)
复制代码
对int[] a 中从fromIndex到toIndex(包头不包尾)之间的元素进行排序.
在这里,Arrays.sort()会自动将int[] work, int workBase, int workLen设置为null,0,0 省去了使用者的麻烦.
紧接着,DualPivotQuicksort.sort()会对传入的int数组进行检测, 具体流程如下: 这里先贴上整个方法的完整源码, 然后按上图中的流程逐步分析, 只想看DualPivotQuicksort的话可以直接跳到下面第7点:
  1. /** * Sorts the specified range of the array using the given * workspace array slice if possible for merging * * @param a the array to be sorted * @param left the index of the first element, inclusive, to be sorted * @param right the index of the last element, inclusive, to be sorted * @param work a workspace array (slice) * @param workBase origin of usable space in work array * @param workLen usable size of work array*/
  2. staticvoidsort(int[] a, intleft, intright,int[] work, intworkBase, intworkLen) {
  3. //Use Quicksort on small arrays if(right - left <QUICKSORT_THRESHOLD) {
  4. sort(a, left, right, true);
  5. return;
  6. }
  7. /*
  8. * Index run[i] is the start of i-th run * (ascending or descending sequence).*/
  9. int[] run = newint[MAX_RUN_COUNT + 1];
  10. intcount = 0; run[0] =left;
  11. //Check if the array is nearly sorted for(intk = left; k < right; run[count] =k) {
  12. if(a[k] < a[k + 1]) { //ascending while(++k <= right & & a[k - 1] <=a[k]);
  13. }elseif(a[k] > a[k + 1]) { //descending while(++k <= right & & a[k - 1] >=a[k]);
  14. for(intlo = run[count] - 1, hi = k; ++lo < --hi; ) {
  15. intt = a[lo]; a[lo] = a[hi]; a[hi] =t;
  16. }
  17. }else{ //equal for(intm = MAX_RUN_LENGTH; ++k <= right & & a[k - 1] ==a[k]; ) {
  18. if(--m == 0) {
  19. sort(a, left, right, true);
  20. return;
  21. }
  22. }
  23. }
  24. /*
  25. * The array is not highly structured, * use Quicksort instead of merge sort.*/
  26. if(++count ==MAX_RUN_COUNT) {
  27. sort(a, left, right, true);
  28. return;
  29. }
  30. }
  31. //Check special cases//Implementation note: variable "right" is increased by 1. if(run[count] == right++) { //The last run contains one element run[++count] =right;
  32. }elseif(count == 1) { //The array is already sorted return;
  33. }
  34. //Determine alternation base for merge byteodd = 0;
  35. for(intn = 1; (n < <= 1) < count; odd ^= 1);
  36. //Use or create temporary array b for merging int[] b; //temp array; alternates with a intao, bo; //array offsets from 'left' intblen = right - left; //space needed for b if(work == null|| workLen < blen || workBase + blen >work.length) {
  37. work = newint[blen];
  38. workBase = 0;
  39. }
  40. if(odd == 0) {
  41. System.arraycopy(a, left, work, workBase, blen);
  42. b =a;
  43. bo = 0;
  44. a =work;
  45. ao = workBase -left;
  46. }else{
  47. b =work;
  48. ao = 0;
  49. bo = workBase -left;
  50. }
  51. //Merging for(intlast; count > 1; count =last) {
  52. for(intk = (last = 0) + 2; k <= count; k += 2) {
  53. inthi = run[k], mi = run[k - 1];
  54. for(inti = run[k - 2], p = i, q = mi; i < hi; ++i) {
  55. if(q >= hi || p < mi & & a[p + ao] <= a[q +ao]) {
  56. b[i + bo] = a[p++ +ao];
  57. }else{
  58. b[i + bo] = a[q++ +ao];
  59. }
  60. }
  61. run[++last] =hi;
  62. }
  63. if((count & 1) != 0) {
  64. for(inti = right, lo = run[count - 1]; --i >=lo;
  65. b[i + bo] = a[i +ao] );
  66. run[++last] =right;
  67. }
  68. int[] t = a; a = b; b =t;
  69. into = ao; ao = bo; bo =o;
  70. }
  71. }
  72. /** * Sorts the specified range of the array by Dual-Pivot Quicksort. * * @param a the array to be sorted * @param left the index of the first element, inclusive, to be sorted * @param right the index of the last element, inclusive, to be sorted * @param leftmost indicates if this part is the leftmost in the range*/
  73. privatestaticvoidsort(int[] a, intleft, intright, boolean leftmost) {
  74. intlength = right - left + 1;
  75. //Use insertion sort on tiny arrays if(length <INSERTION_SORT_THRESHOLD) {
  76. if(leftmost) {
  77. /*
  78. * Traditional (without sentinel) insertion sort, * optimized for server VM, is used in case of * the leftmost part.*/
  79. for(inti = left, j = i; i < right; j = ++i) {
  80. intai = a[i + 1];
  81. while(ai <a[j]) {
  82. a[j + 1] =a[j];
  83. if(j-- ==left) {
  84. break;
  85. }
  86. }
  87. a[j + 1] =ai;
  88. }
  89. }else{
  90. /*
  91. * Skip the longest ascending sequence.*/
  92. do{
  93. if(left >=right) {
  94. return;
  95. }
  96. }while(a[++left] >= a[left - 1]);
  97. /*
  98. * Every element from adjoining part plays the role * of sentinel, therefore this allows us to avoid the * left range check on each iteration. Moreover, we use * the more optimized algorithm, so called pair insertion * sort, which is faster (in the context of Quicksort) * than traditional implementation of insertion sort.*/
  99. for(intk = left; ++left <= right; k = ++left) {
  100. inta1 = a[k], a2 =a[left];
  101. if(a1 <a2) {
  102. a2 = a1; a1 =a[left];
  103. }
  104. while(a1 < a[--k]) {
  105. a[k + 2] =a[k];
  106. }
  107. a[++k + 1] =a1;
  108. while(a2 < a[--k]) {
  109. a[k + 1] =a[k];
  110. }
  111. a[k + 1] =a2;
  112. }
  113. intlast =a[right];
  114. while(last < a[--right]) {
  115. a[right + 1] =a[right];
  116. }
  117. a[right + 1] =last;
  118. }
  119. return;
  120. }
  121. //Inexpensive approximation of length / 7 intseventh = (length > > 3) + (length > > 6) + 1;
  122. /*
  123. * Sort five evenly spaced elements around (and including) the * center element in the range. These elements will be used for * pivot selection as described below. The choice for spacing * these elements was empirically determined to work well on * a wide variety of inputs.*/
  124. inte3 = (left + right) > > > 1; //The midpoint inte2 = e3 -seventh;
  125. inte1 = e2 -seventh;
  126. inte4 = e3 +seventh;
  127. inte5 = e4 +seventh;
  128. //Sort these elements using insertion sort if(a[e2] < a[e1]) { intt = a[e2]; a[e2] = a[e1]; a[e1] =t; }
  129. if(a[e3] < a[e2]) { intt = a[e3]; a[e3] = a[e2]; a[e2] =t;
  130. if(t < a[e1]) { a[e2] = a[e1]; a[e1] =t; }
  131. }
  132. if(a[e4] < a[e3]) { intt = a[e4]; a[e4] = a[e3]; a[e3] =t;
  133. if(t < a[e2]) { a[e3] = a[e2]; a[e2] =t;
  134. if(t < a[e1]) { a[e2] = a[e1]; a[e1] =t; }
  135. }
  136. }
  137. if(a[e5] < a[e4]) { intt = a[e5]; a[e5] = a[e4]; a[e4] =t;
  138. if(t < a[e3]) { a[e4] = a[e3]; a[e3] =t;
  139. if(t < a[e2]) { a[e3] = a[e2]; a[e2] =t;
  140. if(t < a[e1]) { a[e2] = a[e1]; a[e1] =t; }
  141. }
  142. }
  143. }
  144. //Pointers intless = left; //The index of the first element of center part intgreat = 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]) {
  145. /*
  146. * 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.*/
  147. intpivot1 =a[e2];
  148. intpivot2 =a[e4];
  149. /*
  150. * 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.*/
  151. a[e2] =a[left];
  152. a[e4] =a[right];
  153. /*
  154. * Skip elements, which are less or greater than pivot values.*/
  155. while(a[++less] <pivot1);
  156. while(a[--great] >pivot2);
  157. /*
  158. * Partitioning: * * left part center part right part * +--------------------------------------------------------------+ * | < pivot1 | pivot1 <= & & <= pivot2 | ? | > pivot2 | * +--------------------------------------------------------------+ * ^ ^ ^ * | | | * less k great * * Invariants: * * all in (left, less) < pivot1 * pivot1 <= all in [less, k) <= pivot2 * all in (great, right) > pivot2 * * Pointer k is the first index of ?-part.*/
  159. outer:for(intk = less - 1; ++k <=great; ) {
  160. intak =a[k];
  161. if(ak < pivot1) { //Move a[k] to left part a[k] =a[less];
  162. /*
  163. * Here and below we use "a[i] = b; i++;" instead * of "a[i++] = b;" due to performance issue.*/
  164. a[less] =ak;
  165. ++less;
  166. }elseif(ak > pivot2) { //Move a[k] to right part while(a[great] >pivot2) {
  167. if(great-- ==k) {
  168. breakouter;
  169. }
  170. }
  171. if(a[great] < pivot1) { //a[great] <= pivot2 a[k] =a[less];
  172. a[less] =a[great];
  173. ++less;
  174. }else{ //pivot1 <= a[great] <= pivot2 a[k] =a[great];
  175. }
  176. /*
  177. * Here and below we use "a[i] = b; i--;" instead * of "a[i--] = b;" due to performance issue.*/
  178. a[great] =ak;
  179. --great;
  180. }
  181. }
  182. //Swap pivots into their final positions a[left] = a[less - 1]; a[less - 1] =pivot1;
  183. a[right] = a[great + 1]; a[great + 1] =pivot2;
  184. //Sort left and right parts recursively, excluding known pivots sort(a, left, less - 2, leftmost);
  185. sort(a, great + 2, right, false);
  186. /*
  187. * If center part is too large (comprises > 4/7 of the array), * swap internal pivot values to ends.*/
  188. if(less < e1 & & e5 <great) {
  189. /*
  190. * Skip elements, which are equal to pivot values.*/
  191. while(a[less] ==pivot1) {
  192. ++less;
  193. }
  194. while(a[great] ==pivot2) {
  195. --great;
  196. }
  197. /*
  198. * 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.*/
  199. outer:for(intk = less - 1; ++k <=great; ) {
  200. intak =a[k];
  201. if(ak == pivot1) { //Move a[k] to left part a[k] =a[less];
  202. a[less] =ak;
  203. ++less;
  204. }elseif(ak == pivot2) { //Move a[k] to right part while(a[great] ==pivot2) {
  205. if(great-- ==k) {
  206. breakouter;
  207. }
  208. }
  209. if(a[great] == pivot1) { //a[great] < pivot2 a[k] =a[less];
  210. /*
  211. * 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].*/
  212. a[less] =pivot1;
  213. ++less;
  214. }else{ //pivot1 < a[great] < pivot2 a[k] =a[great];
  215. }
  216. a[great] =ak;
  217. --great;
  218. }
  219. }
  220. }
  221. //Sort center part recursively sort(a, less, great, false);
  222. }else{ //Partitioning with one pivot /*
  223. * Use the third of the five sorted elements as pivot. * This value is inexpensive approximation of the median.*/
  224. intpivot =a[e3];
  225. /*
  226. * 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.*/
  227. for(intk = less; k <= great; ++k) {
  228. if(a[k] ==pivot) {
  229. continue;
  230. }
  231. intak =a[k];
  232. if(ak < pivot) { //Move a[k] to left part a[k] =a[less];
  233. a[less] =ak;
  234. ++less;
  235. }else{ //a[k] > pivot - Move a[k] to right part while(a[great] >pivot) {
  236. --great;
  237. }
  238. if(a[great] < pivot) { //a[great] <= pivot a[k] =a[less];
  239. a[less] =a[great];
  240. ++less;
  241. }else{ //a[great] == pivot /*
  242. * 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].*/
  243. a[k] =pivot;
  244. }
  245. a[great] =ak;
  246. --great;
  247. }
  248. }
  249. /*
  250. * Sort left and right parts recursively. * All elements from center part are equal * and, therefore, already sorted.*/
  251. sort(a, left, less - 1, leftmost);
  252. sort(a, great + 1, right, false);
  253. }
  254. }
  255. DualPivotQuickSort.sort()
复制代码
1. 判断数组int[] a的长度是否大于常量QUICKSORT_THRESHOLD, 即286:286是java设定的一个阈值,当数组长度小于此值时, 系统将不再考虑merge sort, 直接将参数传入本类中的另一个私有sort方法进行排序
  1. privatestaticvoidsort(long[] a, intleft, intright, boolean leftmost)
复制代码
  1. //Use Quicksort on small arrays if(right - left <QUICKSORT_THRESHOLD) {
  2. sort(a, left, right, true);
  3. return;
复制代码
2. 继续判断int[] a的长度是否大于常量INSERTION_SORT_THRESHOLD, 即47:
3. 若数组长度小于47, 则使用insertion sort:数组传入本类私有的sort方法后, 会继续判断数组长度是否大于47, 若小于此值, 则直接使用insertion sort并返回结果, 因为插入算法并非本文重点, 此处不再展开叙述
  1. intlength = right - left + 1;
  2. //Use insertion sort on tiny arraysif(length <INSERTION_SORT_THRESHOLD) {
  3. if(leftmost) {
  4. /*
  5. * Traditional (without sentinel) insertion sort, * optimized for server VM, is used in case of * the leftmost part.*/
  6. for(inti = left, j = i; i < right; j = ++i) {
  7. intai = a[i + 1];
  8. while(ai <a[j]) {
  9. a[j + 1] =a[j];
  10. if(j-- ==left) {
  11. break;
  12. }
  13. }
  14. a[j + 1] =ai;
  15. }
  16. }else{
  17. /*
  18. * Skip the longest ascending sequence.*/
  19. do{
  20. if(left >=right) {
  21. return;
  22. }
  23. }while(a[++left] >= a[left - 1]);
  24. /*
  25. * Every element from adjoining part plays the role * of sentinel, therefore this allows us to avoid the * left range check on each iteration. Moreover, we use * the more optimized algorithm, so called pair insertion * sort, which is faster (in the context of Quicksort) * than traditional implementation of insertion sort.*/
  26. for(intk = left; ++left <= right; k = ++left) {
  27. inta1 = a[k], a2 =a[left];
  28. if(a1 <a2) {
  29. a2 = a1; a1 =a[left];
  30. }
  31. while(a1 < a[--k]) {
  32. a[k + 2] =a[k];
  33. }
  34. a[++k + 1] =a1;
  35. while(a2 < a[--k]) {
  36. a[k + 1] =a[k];
  37. }
  38. a[k + 1] =a2;
  39. }
  40. intlast =a[right];
  41. while(last < a[--right]) {
  42. a[right + 1] =a[right];
  43. }
  44. a[right + 1] =last;
  45. }
  46. return;
  47. }
复制代码
判断数组长度是否小于47,若小于则直接使用插入排序
值得注意的是, java在这里提供了两种不同的插入排序算法, 当传入的参数leftmost真假值不同时, 会使用不同的算法. leftmost代表的是本次传入的数组是否是从最初的int[] a的最左侧left开始的, 因为本方法在整个排序过程中可能会针对数组的不同部分被多次调用, 因此leftmost有可能为false.
Quicksort的情况我们放到最后再谈, 这里先回过来看第一步判断中数组长度大于286的情形, 这种情况下, 系统会
4.继续判断该数组是否已经高度结构化(即已经接近排序完成):这里的基本思路是这样的: a. 定义一个常量MAX_RUN_COUNT = 67;b. 定义一个计数器int count = 0; 定义一个数组int[] run 使之长度为MAX_RUN_COUNT + 1;c. 令run[0] = left, 然后从传入数组的最左侧left开始遍历, 若数组的前n个元素均为升序/降序排列, 而第n + 1个元素的升/降序发生了改变, 则将第n个元素的索引存入run[1], 同时++count, 此时count的值为1;d. 从n + 1开始继续遍历, 直至升/降序再次改变, 再将此处的索引存入run[2], ++count, 此时count的值为2, 以此类推... ...... e. 若将整个数组全部遍历完成后, count仍然小于MAX_RUN_COUNT (即整个数组升降序改变的次数低于67次), 证明该数组是高度结构化的, 则使用merge sort进行排序; 若count == MAX_RUN_COUNT时, 还未完成对数组的遍历, 则证明数组并非高度结构化, 则调用前文所述私有sort方法进行quicksort.
  1. /*
  2. * Index run[i] is the start of i-th run * (ascending or descending sequence).*/
  3. int[] run = newint[MAX_RUN_COUNT + 1];
  4. intcount = 0; run[0] =left;
  5. //Check if the array is nearly sortedfor(intk = left; k < right; run[count] =k) {
  6. if(a[k] < a[k + 1]) { //ascending while(++k <= right & & a[k - 1] <=a[k]);
  7. }elseif(a[k] > a[k + 1]) { //descending while(++k <= right & & a[k - 1] >=a[k]);
  8. for(intlo = run[count] - 1, hi = k; ++lo < --hi; ) {
  9. intt = a[lo]; a[lo] = a[hi]; a[hi] =t;
  10. }
  11. }else{ //equal for(intm = MAX_RUN_LENGTH; ++k <= right & & a[k - 1] ==a[k]; ) {
  12. if(--m == 0) {
  13. sort(a, left, right, true);
  14. return;
  15. }
  16. }
  17. }
  18. /*
  19. * The array is not highly structured, * use Quicksort instead of merge sort.*/
  20. if(++count ==MAX_RUN_COUNT) {
  21. sort(a, left, right, true);
  22. return;
  23. }
  24. }
复制代码
判断该数组是否已经高度结构化
5. 判断该数组是否是是已经排列好的:若该数组是高度结构化的, 在使用merge sort进行排序之前, 会先检验数组是否本身就是排序好的, 思路很简单, 如果在前面的检测中一次就完成了遍历, 就证明该数组是排序好的, 则直接返回结果:
  1. //Check special cases
  2. //Implementation note: variable "right" is increased by 1.if(run[count] == right++) { //The last run contains one element run[++count] =right;
  3. }elseif(count == 1) { //The array is already sorted return;
  4. }
复制代码
判断数组是否本来就是排列好的
*当然, 在具体实现中还有不少其他要考虑的因素, 有兴趣了解的话可以结合上一部分代码进行阅读.
6. 进行归并排序(merge sort):此处不再展开叙述, 值得注意的是, 由于归并算法在操作过程中需要使用一块额外的存储空间, 本方法参数列表中要求的work, workBase和workLen三个参数就是在此处使用的:
  1. //Determine alternation base for mergebyteodd = 0;
  2. for(intn = 1; (n < <= 1) < count; odd ^= 1);
  3. //Use or create temporary array b for mergingint[] b; //temp array; alternates with aintao, bo; //array offsets from 'left'intblen = right - left; //space needed for bif(work == null|| workLen < blen || workBase + blen >work.length) {
  4. work = newint[blen];
  5. workBase = 0;
  6. }
  7. if(odd == 0) {
  8. System.arraycopy(a, left, work, workBase, blen);
  9. b =a;
  10. bo = 0;
  11. a =work;
  12. ao = workBase -left;
  13. }else{
  14. b =work;
  15. ao = 0;
  16. bo = workBase -left;
  17. }
  18. //Mergingfor(intlast; count > 1; count =last) {
  19. for(intk = (last = 0) + 2; k <= count; k += 2) {
  20. inthi = run[k], mi = run[k - 1];
  21. for(inti = run[k - 2], p = i, q = mi; i < hi; ++i) {
  22. if(q >= hi || p < mi & & a[p + ao] <= a[q +ao]) {
  23. b[i + bo] = a[p++ +ao];
  24. }else{
  25. b[i + bo] = a[q++ +ao];
  26. }
  27. }
  28. run[++last] =hi;
  29. }
  30. if((count & 1) != 0) {
  31. for(inti = right, lo = run[count - 1]; --i >=lo;
  32. b[i + bo] = a[i +ao] );
  33. run[++last] =right;
  34. }
  35. int[] t = a; a = b; b =t;
  36. into = ao; ao = bo; bo =o;
  37. }
  38. merge sort
复制代码
7. 进行双基准快速排序(dual pivot quicksort):只有在上述情况都不满足的情况下, 本方法才会使用双基准快速排序算法进行排序, 算法本身的思路并不复杂, 和经典快速排序相差不大, 顾名思义, 比起经典快排, 该算法选取了两个Pivot, 我们姑且称之为P1和P2. P1和P2都从数组中选出, P1在P2的右侧, 且P1必须小于P2, 如果不是, 则交换P1和P2的值;接下来令数组中的每一个元素和基准进行比较, 比P1小的放在P1左边, 比P2大的放在P2右边, 介于两者之间的放在中间. 这样, 最终我们会的得到三个数组, 比P1小元素构成的数组, 介于P1和P2之间的元素构成的数组, 以及比P2大的元素构成的数组. 最后, 递归地对这三个数组进行排序, 最终得到排序完成的结果.
思路上虽然, 并不复杂, 但Java为了尽可能的提高效率, 在对这个算法进行实现的过程中增加了非常多的细节, 下面我们就来大致看一下其中的部分内容:
  1. //Inexpensive approximation of length / 7intseventh = (length > > 3) + (length > > 6) + 1;
  2. /*
  3. * Sort five evenly spaced elements around (and including) the * center element in the range. These elements will be used for * pivot selection as described below. The choice for spacing * these elements was empirically determined to work well on * a wide variety of inputs.*/
  4. inte3 = (left + right) > > > 1; //The midpointinte2 = e3 -seventh;
  5. inte1 = e2 -seventh;
  6. inte4 = e3 +seventh;
  7. inte5 = e4 +seventh;
  8. //Sort these elements using insertion sortif(a[e2] < a[e1]) { intt = a[e2]; a[e2] = a[e1]; a[e1] =t; }
  9. if(a[e3] < a[e2]) { intt = a[e3]; a[e3] = a[e2]; a[e2] =t;
  10. if(t < a[e1]) { a[e2] = a[e1]; a[e1] =t; }
  11. }
  12. if(a[e4] < a[e3]) { intt = a[e4]; a[e4] = a[e3]; a[e3] =t;
  13. if(t < a[e2]) { a[e3] = a[e2]; a[e2] =t;
  14. if(t < a[e1]) { a[e2] = a[e1]; a[e1] =t; }
  15. }
  16. }
  17. if(a[e5] < a[e4]) { intt = a[e5]; a[e5] = a[e4]; a[e4] =t;
  18. if(t < a[e3]) { a[e4] = a[e3]; a[e3] =t;
  19. if(t < a[e2]) { a[e3] = a[e2]; a[e2] =t;
  20. if(t < a[e1]) { a[e2] = a[e1]; a[e1] =t; }
  21. }
  22. }
  23. }
  24. //Pointersintless = left; //The index of the first element of center partintgreat = right; //The index before the first element of right partif(a[e1] != a[e2] & & a[e2] != a[e3] & & a[e3] != a[e4] & & a[e4] !=a[e5]) {
  25. /*
  26. * 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.*/
  27. intpivot1 =a[e2];
  28. intpivot2 =a[e4];
  29. /*
  30. * 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.*/
  31. a[e2] =a[left];
  32. a[e4] =a[right];
  33. /*
  34. * Skip elements, which are less or greater than pivot values.*/
  35. while(a[++less] <pivot1);
  36. while(a[--great] >pivot2);
  37. /*
  38. * Partitioning: * * left part center part right part * +--------------------------------------------------------------+ * | < pivot1 | pivot1 <= & & <= pivot2 | ? | > pivot2 | * +--------------------------------------------------------------+ * ^ ^ ^ * | | | * less k great * * Invariants: * * all in (left, less) < pivot1 * pivot1 <= all in [less, k) <= pivot2 * all in (great, right) > pivot2 * * Pointer k is the first index of ?-part.*/
  39. outer:for(intk = less - 1; ++k <=great; ) {
  40. intak =a[k];
  41. if(ak < pivot1) { //Move a[k] to left part a[k] =a[less];
  42. /*
  43. * Here and below we use "a[i] = b; i++;" instead * of "a[i++] = b;" due to performance issue.*/
  44. a[less] =ak;
  45. ++less;
  46. }elseif(ak > pivot2) { //Move a[k] to right part while(a[great] >pivot2) {
  47. if(great-- ==k) {
  48. breakouter;
  49. }
  50. }
  51. if(a[great] < pivot1) { //a[great] <= pivot2 a[k] =a[less];
  52. a[less] =a[great];
  53. ++less;
  54. }else{ //pivot1 <= a[great] <= pivot2 a[k] =a[great];
  55. }
  56. /*
  57. * Here and below we use "a[i] = b; i--;" instead * of "a[i--] = b;" due to performance issue.*/
  58. a[great] =ak;
  59. --great;
  60. }
  61. }
  62. //Swap pivots into their final positions a[left] = a[less - 1]; a[less - 1] =pivot1;
  63. a[right] = a[great + 1]; a[great + 1] =pivot2;
  64. //Sort left and right parts recursively, excluding known pivots sort(a, left, less - 2, leftmost);
  65. sort(a, great + 2, right, false);
  66. /*
  67. * If center part is too large (comprises > 4/7 of the array), * swap internal pivot values to ends.*/
  68. if(less < e1 & & e5 <great) {
  69. /*
  70. * Skip elements, which are equal to pivot values.*/
  71. while(a[less] ==pivot1) {
  72. ++less;
  73. }
  74. while(a[great] ==pivot2) {
  75. --great;
  76. }
  77. /*
  78. * 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.*/
  79. outer:for(intk = less - 1; ++k <=great; ) {
  80. intak =a[k];
  81. if(ak == pivot1) { //Move a[k] to left part a[k] =a[less];
  82. a[less] =ak;
  83. ++less;
  84. }elseif(ak == pivot2) { //Move a[k] to right part while(a[great] ==pivot2) {
  85. if(great-- ==k) {
  86. breakouter;
  87. }
  88. }
  89. if(a[great] == pivot1) { //a[great] < pivot2 a[k] =a[less];
  90. /*
  91. * 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].*/
  92. a[less] =pivot1;
  93. ++less;
  94. }else{ //pivot1 < a[great] < pivot2 a[k] =a[great];
  95. }
  96. a[great] =ak;
  97. --great;
  98. }
  99. }
  100. }
  101. //Sort center part recursively sort(a, less, great, false);
  102. }else{ //Partitioning with one pivot /*
  103. * Use the third of the five sorted elements as pivot. * This value is inexpensive approximation of the median.*/
  104. intpivot =a[e3];
  105. /*
  106. * 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.*/
  107. for(intk = less; k <= great; ++k) {
  108. if(a[k] ==pivot) {
  109. continue;
  110. }
  111. intak =a[k];
  112. if(ak < pivot) { //Move a[k] to left part a[k] =a[less];
  113. a[less] =ak;
  114. ++less;
  115. }else{ //a[k] > pivot - Move a[k] to right part while(a[great] >pivot) {
  116. --great;
  117. }
  118. if(a[great] < pivot) { //a[great] <= pivot a[k] =a[less];
  119. a[less] =a[great];
  120. ++less;
  121. }else{ //a[great] == pivot /*
  122. * 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].*/
  123. a[k] =pivot;
  124. }
  125. a[great] =ak;
  126. --great;
  127. }
  128. }
  129. /*
  130. * Sort left and right parts recursively. * All elements from center part are equal * and, therefore, already sorted.*/
  131. sort(a, left, less - 1, leftmost);
  132. sort(a, great + 1, right, false);
  133. }
复制代码
先贴上这部分完整的代码
首先, 也是本方法中最具特色的部分, 就是对Pivot的选取:
在这里, 系统会先通过位运算获取数组长度的1/7的近似值(位运算无法精确表示1/7)
  1. intseventh = (length > > 3) + (length > > 6) + 1;
复制代码
然后获取本数组中间位置的索引e3:
  1. inte3 = (left + right) > > > 1; //The midpoint
复制代码
在中间位置的左右1/7, 2/7处各获取两个索引(e1, e2, e4, e5):
  1. inte2 = e3 -seventh;
  2. inte1 = e2 -seventh;
  3. inte4 = e3 +seventh;
  4. inte5 = e4 + seventh;
复制代码
将这五个索引对应的值用插入算法进行有小到大的排序后, 再放回五个索引的位置
  1. //Sort these elements using insertion sortif(a[e2] < a[e1]) { intt = a[e2]; a[e2] = a[e1]; a[e1] =t; }
  2. if(a[e3] < a[e2]) { intt = a[e3]; a[e3] = a[e2]; a[e2] =t;
  3. if(t < a[e1]) { a[e2] = a[e1]; a[e1] =t; }
  4. }
  5. if(a[e4] < a[e3]) { intt = a[e4]; a[e4] = a[e3]; a[e3] =t;
  6. if(t < a[e2]) { a[e3] = a[e2]; a[e2] =t;
  7. if(t < a[e1]) { a[e2] = a[e1]; a[e1] =t; }
  8. }
  9. }
  10. if(a[e5] < a[e4]) { intt = a[e5]; a[e5] = a[e4]; a[e4] =t;
  11. if(t < a[e3]) { a[e4] = a[e3]; a[e3] =t;
  12. if(t < a[e2]) { a[e3] = a[e2]; a[e2] =t;
  13. if(t < a[e1]) { a[e2] = a[e1]; a[e1] =t; }
  14. }
  15. }
  16. }
复制代码
对索引的值排序
接下来进行判断, 若这五个索引对应的元素值各不相同, 则选取e2的值作为Pivot1, e4的值作为Pivot2(特别注意基准是值而不是元素), 然后进行双基准快排, Java声称这种选法比其他方式更加高效;但如果这五个值中有相同的存在, 则本轮排序选取e3的值作为Pivot, 进行单基准快排, 同样, Java声称这种选取方式要比随机选取更加高效.
至于具体排序的部分, 其实并没有太多可以叙述的内容, 值得注意的是, 由于在递归的过程中会不断地调用私有的sort方法, 所以在递归中获得的子数组长度小47时, 会改为调用插入排序. 此外, 源码中还有一些可以借鉴的用来提高效率的小窍门, 比如在对元素进行交换位置之前先过滤掉头尾处已经在正确位置的元素等, 有兴趣的话可以再对源码进行仔细阅读.
至此, 关于DualPivotQuicksort.sort()的大致实现过程的介绍也就基本结束了, 最后我们不妨进行一个简单的测试, 看看它是否真的比经典快排更加高效: 首先, 我们先来测试一下经典Quicksort的性能, 对包含一亿个Random.nextInt()随机数的数组进行排序, 重复十次求平均排序运行时间, 具体代码如下, 其中经典快排的代码摘自wiki快速排序条目:
  1. import java.util.Date;
  2. import java.util.Random;
  3. publicclassTest {
  4. publicstaticvoidmain(String[] args) {
  5. //定义time记录总耗时 inttime = 0;
  6. //测试十次 for(inti = 0; i < 10; i++) {
  7. //生成一个包含一亿个Random.nextInt()随机数的数组 Random r = newRandom();
  8. int[] arr = newint[100000000];
  9. for(intj : arr) {
  10. arr[j] =r.nextInt();
  11. }
  12. //使用经典快排对数组进行排序,并获取运行时间 longt1 = newDate().getTime();
  13. qSort(arr, 0, arr.length - 1);
  14. longt2 = newDate().getTime();
  15. //输出运行时间 System.out.print((int)(t2 - t1) + "");
  16. //对每次运行时间求和 time += (int)(t2 -t1);
  17. }
  18. //输出十次排序平均运行时间 System.out.println(time / 10);
  19. }
  20. publicstaticvoidqSort(int[] arr, inthead, inttail) {
  21. if(head >= tail || arr == null|| arr.length <= 1) {
  22. return;
  23. }
  24. inti = head, j = tail, pivot = arr[(head + tail) / 2];
  25. while(i <=j) {
  26. while(arr[i] <pivot) {
  27. ++i;
  28. }
  29. while(arr[j] >pivot) {
  30. --j;
  31. }
  32. if(i <j) {
  33. intt =arr[i];
  34. arr[i] =arr[j];
  35. arr[j] =t;
  36. ++i;
  37. --j;
  38. }elseif(i ==j) {
  39. ++i;
  40. }
  41. }
  42. qSort(arr, head, j);
  43. qSort(arr, i, tail);
  44. }
  45. }
复制代码
经典快排测试
经过测试, 我们得到结果, 十次排序的运行时间分别为2405 3017 3021 2972 2993 2967 2992 2954 3001 2984(ms),
平均时间则是2930ms
接下来, 再对DualPivotQuicksort.sort()使用同样的方法进行测试, 直接用Arrays.sort()进行排序,代码如下:
  1. import java.util.Arrays;
  2. import java.util.Date;
  3. import java.util.Random;
  4. publicclassTest2 {
  5. publicstaticvoidmain(String[] args) {
  6. //定义time记录总耗时 inttime = 0;
  7. //测试十次 for(inti = 0; i < 10; i++) {
  8. //生成一个包含一亿个Random.nextInt()随机数的数组 Random r = newRandom();
  9. int[] arr = newint[100000000];
  10. for(intj : arr) {
  11. arr[j] =r.nextInt();
  12. }
  13. //使用经典快排对数组进行排序,并获取运行时间 longt1 = newDate().getTime();
  14. Arrays.sort(arr);
  15. longt2 = newDate().getTime();
  16. //输出运行时间 System.out.print((int)(t2 - t1) + "");
  17. //对每次运行时间求和 time += (int)(t2 -t1);
  18. }
  19. //输出十次排序平均运行时间 System.out.println(time / 10);
  20. }
  21. }
复制代码
双基准快排测试
十次运行时间分别是115 16 31 21 28 118 62 78 78 63(ms).
平均时间则达到了惊人的61ms.
当然, 之所以会产生如此巨大的差距, 一方面是因为双基准快排本身性能更加优秀, 另一方也是因为Java对该方法进行了大量的优化, 而选取测试的经典快排则相当粗糙, 只是这种算法思想的体现, 并不是说两种算法本身性能上存在着这种程度的差距. Reference:
Quicksort - wiki https://en.wikipedia.org/wiki/Quicksort
快速排序 - wiki https://zh.wikipedia.org/zh-cn/%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F
java.util.Arrays java.util.DualPivotQuicksort
该用户未在地球留下任何的痕迹

本版积分规则

QQ|小黑屋|帮助|IT技术擎 ( 沪ICP备15054863号  

GMT+8, 2018-8-22 15:50

Powered by Discuz! X3.2 Licensed

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表