staticvoidsort(int[] a, int left, int right, int[] work, int workBase, int workLen){ // Use Quicksort on small arrays 对小数组使用快速排序 if (right - left < QUICKSORT_THRESHOLD) { sort(a, left, right, true); return; }
privatestaticvoidsort(int[] a, int left, int right, boolean leftmost){ int length = right - left + 1; // Use insertion sort on tiny arrays 对极小数组使用插入排 if (length < INSERTION_SORT_THRESHOLD) { if (leftmost) { 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; }
如果元素个数小于286,同时又大于47,则使用双轴快排。
双轴快排的基本思想是:
从数组中选取 5 个均匀间隔的元素,并将这 5 个元素进行插入排序。
1 2 3 4 5 6 7 8 9 10 11 12
/* * 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. */ int e3 = (left + right) >>> 1; // The midpoint int e2 = e3 - seventh; int e1 = e2 - seventh; int e4 = e3 + seventh; int e5 = e4 + seventh;
使用五个排序元素中的第二个和第四个作为枢轴,且 pivot1 <= pivot2。
定义两个指针 less 与 great ,less 从数组最左端向右遍历,直到找到第一个不小于枢纽1的元素,great 从数组最右端向左遍历,直到找到第一个不大于枢纽2的元素。
1 2 3 4 5 6 7 8
// 指针 int less = left; // The index of the first element of center part int great = right; // The index before the first element of right part
//......
while (a[++less] < pivot1); while (a[--great] > pivot2);
此时再将 less 与 great 中间的元素进行移动,将小于枢纽1的元素移至枢纽1左边,将大于枢纽2的元素移至枢纽2右边,最后位于两个枢纽之间的元素就是 pivot1 <= && <= pivot2 的元素了。