排序算法在JDK中的应用

JDK8中的排序算法

JDK中对于数组的排序使用比较的多的是Arrays.sort()和Arrays.parallelSort(),前者是传统的排序算法,后者是JDK8新增的并行排序算法,基于fork/join框架,今天主要是分析Arrays.sort()的底层实现。
Arrays.sort()可以对所有的基本类型(除boolean)和Object进行排序,如果是数值类型的数就直接按照从大到小的顺序排列,如果是String类型的数组就按照其ASCII码进行排序,如果是对象就按照对象内部实现的compareTo()方法进行比较排序,并且使用的是归并排序。
这里我们通过分析Arrays.sort(int[] a)来分析一下JDK的实现流程和方式。

外层方法

第一步,调用Arrays.sort(int[] a)后,直接调用了DualPivotQuicksort.sort()字面意思是双轴快速排序,如下面代码所示。

/**
     * Sorts the specified array into ascending numerical order.
     * 将数组按照升序排列
     * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
     * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
     * offers O(n log(n)) performance on many data sets that cause other
     * quicksorts to degrade to quadratic performance, and is typically
     * faster than traditional (one-pivot) Quicksort implementations.
     * 简单的翻译:算法的三个大佬作者。这个双轴快速排序可以为那些让传统快速排序性能下降的数据集提供O(n log(n))的时间复杂度,所以速度比传统的快速排序快
     * 这里是为什么双轴快排比普通快排更快的Paper:https://arxiv.org/pdf/1511.01138.pdf
     * 另外一个博主的笔记:https://www.jianshu.com/p/2c6f79e8ce6e
     * @param a the array to be sorted
     */
    public static void sort(int[] a) {
        DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
    }

改进后的归并排序

现在我们继续跟踪代码进入sort()的内部实现:

   /**
     * 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  工作辅助数组的长度
     * 此代码我进行了一些缩进和对齐
     */
    static void sort(int[] a, int left, int right,int[] work, int workBase, int workLen) {
        // Use Quicksort on small arrays
        //If the length of an array to be sorted is less than this constant, Quicksort is used in preference to merge sort.
        //当待排序的数组长度小于286时使用快速排序,这时快排的表现好于归并排序
        // private static final int QUICKSORT_THRESHOLD = 286;
        if (right - left < QUICKSORT_THRESHOLD){
            sort(a, left, right, true);
            return;
        }
        /*
         * Index run[i] is the start of i-th run
         * (ascending or descending sequence). 
         * 设置run数组第一个位置即需要排序的序列的第一个元素,长度就是是否有序的临界值
         * //The maximum number of runs in merge sort.
         * private static final int MAX_RUN_COUNT = 67;
         */
        int[] run = new int[MAX_RUN_COUNT + 1];
        int count = 0; run[0] = left;

        // Check if the array is nearly sorted
        //检查数组是否接近有序(无序程度)
        //这里的检查思路是:任一的数组都可以分割成若干个递增或递减的数组,比如{12,33,2,10,23,21,15}可以分成{12,33},{2,10,23},{21,15}这三个子数组要么是递增的要么是递减的
        //上面的run数组就是用于存取子数组开始的下标的,然后通过比较run数组中元素个数来确定数组是否基本有序。如果大于MAX_RUN_COUNT那么就认定数组基本无序
        for (int k = left; k < right; run[count] = k) {
            // ascending 处理递增数组的位置 
            if (a[k] < a[k + 1]) { 
                while (++k <= right && a[k - 1] <= a[k]);
                // descending 处理递减数组的位置
            } else if (a[k] > a[k + 1]) { 
                while (++k <= right && a[k - 1] >= a[k]);
                //同时将其转换为递增
                for (int lo = run[count] - 1, hi = k; ++lo < --hi; ) {
                    int t = a[lo]; a[lo] = a[hi]; a[hi] = t;
                }
                // equal 处理相等元素
            } else { 
                //The maximum length of run in merge sort. 归并排序的最多运行次数
                //private static final int MAX_RUN_LENGTH = 33;
                //这一步的意思是如果相等的序列等于MAX_RUN_LENGTH就直接执行快速排序。*不是很不清楚为什么要这么做*
                for (int m = MAX_RUN_LENGTH; ++k <= right && a[k - 1] == a[k]; ) {                  
                    if (--m == 0) {
                        sort(a, left, right, true);
                        return;
                    }
                } 
            }

            /*
             * The array is not highly structured,
             * use Quicksort instead of merge sort.
             * 每次循环完成检查count值是否已经等于无序临界值,如果直接等于临界值,那么就直接使用快速排序
             * 待排序列越接近有序,归并排序效率越高
             */
            if (++count == MAX_RUN_COUNT) {
                sort(a, left, right, true);
                return;
            }
        }

        // Check special cases 检查特殊的情况
        // Implementation note: variable "right" is increased by 1.在right变量的基础上加1
        if (run[count] == right++) { // The last run contains one element run数组的最后添加一个哨兵元素,值为right+1
            run[++count] = right;
        } else if (count == 1) { // The array is already sorted 如果只有一个单调序列那么说明数组本身就是有序的 直接跳出
            return;
        }

        //这下面就是归并排序的相关操作了,到这一步时说明数组通过了初步筛选,即数组长度大于286且接近有序
        // Determine alternation base for merge 确定归并排序的交替标准
        byte odd = 0;
        for (int n = 1; (n <<= 1) < count; odd ^= 1);
        // Use or create temporary array b for merging 为归并使用或者创建一个临时数组
        int[] b;                 // temp array; alternates with a 临时数组,为a归并时提供临时存储,即辅助空间
        int ao, bo;              // array offsets from 'left'设置偏移指针
        int blen = right - left; // space needed for b 数组b需要的长度
        //操作work数组的相关属性
        if (work == null || workLen < blen || workBase + blen > work.length) {
            work = new int[blen];
            workBase = 0;
        }
        //通过odd确定a b数组的内容
        //通过此操作后 a和b中必然有一个为原数组有一个为作为辅助空间的数组
        if (odd == 0) {
            System.arraycopy(a, left, work, workBase, blen);
            b = a;
            bo = 0;
            a = work;
            ao = workBase - left;
        } else {
            b = work;
            ao = 0;
            bo = workBase - left;
        }

        // Merging 归并操作
        for (int last; count > 1; count = last) { //归并次数边界
            //具体的归并过程 
            for (int k = (last = 0) + 2; k <= count; k += 2) {
                int hi = run[k], mi = run[k - 1];
                for (int i = run[k - 2], p = i, q = mi; i < hi; ++i) {
                    if (q >= hi || p < mi && a[p + ao] <= a[q + ao]) {
                        b[i + bo] = a[p++ + ao];
                    } else {
                        b[i + bo] = a[q++ + ao];
                    }
                }
                run[++last] = hi;
            }
            //如果其中的一个子序列元素个数为奇数,就直接把这个序列复制到b中
            if ((count & 1) != 0) {
                for (int i = right, lo = run[count - 1]; --i >= lo;
                    b[i + bo] = a[i + ao]
                );
                run[++last] = right;
            }
            //交换数组,更新指针,准备进行下一次归并
            int[] t = a; a = b; b = t;
            int o = ao; ao = bo; bo = o;
        }
    }

以上便是JDK对于sort排序中归并排序部分的优化处理,总结而言就是当待排序的数组长度大于等于286时开始考虑使用归并排序。在此同时还需要考虑的条件是待排序的数组是否是基本有序的,JDK采用的办法是将待排序数组分成若干个单调递增或者递减的数组,如果分成的小数组的个数
大于67就认为这个数组基本上是无序的此时就直接调用了快速排序,还有个我不是很理解的条件就是当带待排序的数组中相等的元素子序列长度大于等于MAX_RUN_LENGTH(33)时就直接使用快速排序。

改进后的快速排序

在分析上述代码时,可以发现程序会在特殊的情况调用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语言全部写一遍。

参考

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值