欢迎点击「算法与编程之美」↑关注我们!
本文首发于微信公众号:"算法与编程之美",欢迎关注,及时了解更多此系列文章。
改进后的快速排序
在分析上述代码时,可以发现程序会在特殊的情况调用sort()方法即改进后得快速排序,接下来就来分析sort()快速排序的代码实现。
/**
* 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 leftmost表示该部分是否是范围内最左的部分
*/
private static void sort(int[] a, int left, int right, boolean leftmost) {
int length = right - left + 1;
// Use insertion sort on tiny arrays
//当数组的长度很小时就是用插入排序,INSERTION_SORT_THRESHOLD=47
if (length < INSERTION_SORT_THRESHOLD) {
if (leftmost) {
/*
* Traditional (without sentinel) insertion sort, 传统的插入排序,不使用哨兵元素
* optimized for server VM, is used in case of 针对最左边的部分的情况进行了服务器虚拟机的优化
* the leftmost part.
*/
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 {
/*
* Skip the longest ascending sequence. 跳过最长的升序情况,提高算法效率
*/
do {
if (left >= right) {
return;
}
} while (a[++left] >= a[left - 1]);
/*
* 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()方法的数组)他比传统的
* sort, which is faster (in the context of Quicksort) 插入排序更快
* than traditional implementation of insertion sort.
*/
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;
}
//从这里开始是对待排序的元素进行分组处理
// Inexpensive approximation of length / 7
// 使用length/7作为近似的加权长度
int seventh = (length >> 3) + (length >> 6) + 1;
/*
* Sort five evenly spaced elements around (and including) the 在范围内的中心元素附近找到5个均匀间隔的元素
* 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.
*/
int e3 = (left + right) >>> 1; // The midpoint
int e2 = e3 - seventh;
int e1 = e2 - seventh;
int e4 = e3 + seventh;
int e5 = e4 + seventh;
// Sort these elements using insertion sort 使用插入排序对这些元素进行排序
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; }
}
}
}//分组完成
// Pointers 指针
int less = left; // The index of the first element of center part 中心部分第一个元素的位置
int 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 因为有上面的排序 所以在这里pivot1 <= pivot2
* 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];
/*
* Skip elements, which are less or greater than pivot values.
* 筛选那些比枢轴元素更大或者更小的元素 以此来确定less和great的位置
*/
while (a[++less] < pivot1);
while (a[--great] > pivot2);
/*
* 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.
* 以下的forless-1开始向右遍历至great,把小于pivot1的元素移动到less左边,大于pivot2的元素移动到great右边。
*/
//outer标签
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.
* 在这里分开写的原因是因为前者效率更佳
* 想要了解的可以看这里的讨论:https://www.oschina.net/question/3037675_2206753
*/
a[less] = ak;
++less;
} else if (ak > pivot2) { // Move a[k] to right part
while (a[great] > pivot2) {
if (great-- == k) {
break outer;
}
}
//通过上面已知great<pivot2,但是并不知道great和pivot1的大小关系,
//如果它比pivot1还小,需要移动到到less左边,否则只需要交换到k处。
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
// 将less-1的元素放到对头,great+1的元素放在队尾
//然后将pivot1放在less-1,pivot2放在great+1
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.
* 如果中心部分太大(大小超过了整个数组的4/7),就将内部的枢轴值交换到端点
*/
if (less < e1 && e5 < great) {
/*
* Skip elements, which are equal to pivot values.
* 调整less和great指针的位置,即跳过相等的元素
*/
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];
/*
* 浮点零的相关问题:https://stackoverflow.com/questions/13544342/why-do-floating-point-numbers-have-signed-zeros
* Even though a[great] equals to pivot1, the 如果a[great]和pivot1是不同符号的浮点零,
* assignment a[less] = pivot1 may be incorrect, 即使a[great]这个元素等于pivot1,“a[less] = pivot1”这个赋值操作也可能是不正确的
* if a[great] and pivot1 are floating-point zeros (这里是对单双精度元素排序的一个特例处理,使-0排在+0之前)
* of different signs. Therefore in float and 因此在单双精度的排序算法中我们必须使用更加精确的赋值即a[less]=a[great]
* 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. 使用5个排序好的元素中的第三个作为枢轴元素
* This value is inexpensive approximation of the median. 这个值是数组的中值近似值
*/
int pivot = a[e3];
/*
* Partitioning degenerates to the traditional 3-way 分区方式退化为传统的3路形式
* (or "Dutch National Flag") schema:(或者“荷兰国旗”模式)
* 荷兰国旗问题(Dutch National Flag Problem):https://www.cnblogs.com/freelancy/p/7940803.html
* 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);
}
}
解决方案
上述代码便是jdk1.8中快速排序sort()的源码部分,总结一下主要有以下几个要点
当待排数组的长度小于47时就会直接使用插入排序
选择五个均匀间隔的元素作为使用不同快速排序方法的判断标准
如果五个元素互不相等那么使用双轴快速排序(两个枢轴为e2和e4)
否则使用只有一个枢轴值(e3)进行排序,但是这里还是把待排序数组分成了三个部分分别是大于,等于和小于枢轴的区域
结语
写了好久终于把这篇博客写好了,过程中查了好多的资料看了好多的博客,不过最后还是把这个坑填上了,收获颇多。
写JDK源码的大佬是真的好厉害,注释很清晰,可惜有些注释不能翻译得很准确,还是要提高英语水平。
阅读源码的能力还是要多提升,这次看注释+博客和边调试边理解的方式还是挺不错的。
多学习 多阅读 多思考
PS
排序算法写得差不了,接下来准备把数据结构的内容用Java语言全部写一遍。争取在9月份之前完成这个目标。
参考文献
双轴快排原理解析
JDK源码解析(1)
END
主 编 | 张祯悦
责 编 | 杨 旭
where2go 团队
微信号:算法与编程之美
长按识别二维码关注我们!
温馨提示: 点击页面右下角 “写留言”发表评论,期待您的参与!期待您的转发!