JDK源码解析(1)——数据数组排序:Arrays.sort()

本文详细解析了JDK中Arrays.sort()方法实现数据数组排序的原理,包括对基本数据类型数组的排序实现。该方法采用了结合归并排序和改进的快速排序算法,对数组进行高效排序。通过对源码的分析,探讨了算法的优化策略,如针对小数组的插入排序、双枢轴快速排序等。同时,文章提出了几个疑问,包括等值序列处理、分位点选取依据、代码风格等。
摘要由CSDN通过智能技术生成
 (p.s:程序员应该多读代码,特别是前人写的代码。好的程序员对于代码应该有敏锐的“感知能力”,一看到代码就头昏眼花的,注定不是合格的程序员,更谈不上软件工程师 。。。。俺是这么认为的 。今天下载了JDK源代码文件,随便看了看,感觉蛮有收获。。。。。 )

概述:
    JDK提供了对于数组排序的库函数,java.util.Arrays类中的一些列重载的sort的方法为给定数组进行排序,以下是各个重载方法签名:
<span style="font-family:KaiTi_GB2312;font-size:18px;">void sort (char[])
void sort (char[], int, int)
void sort (byte[])
void sort (byte[], int, int)
void sort (T[], Comparator)
void sort (short[], int, int)
void sort (short)
void sort (double[], int, int)
void sort (Object[])
void sort (Object[], int, int)
void sort (T[], int, int, Comparator)
void sort (double[])
void sort (float[], int, int)
void sort (float[])
void sort (int[], int, int)
void sort (long[])
void sort (long[], int, int)
void sort (long[]) </span>
 
    对于这些sort方法,我们可以从不同的角度分类:
    根据第一个参数的类型,可以将这些方法分为3类:基本数据类型数组的数值排序方法,提供了对于byte,short,int,long,char,float,double这些基本数据类型的数组的排序方法;自定义类的对象数组排序方法。提供了对于任意类类型个数组的排序方法,这些方法的输入参数为Object数组;泛型方法提供了泛型对象数组的排序实现。
    根据参数的个数,可以将这些方法分为3类:包含1个参数的方法对整个数组排序,包含3个参数的方法对数组的一部分进行排序,后两个参数确定了数组中要排序元素的范围;泛型方法中包含比较元素大小时使用的比较器类。
    根据实现的原理,可以将这些方法分为2类:数据数组排序方法采用一种结合了归并排序、插入排序、改进后的快速排序算法来实现,这些方法提供了以上7种基本数据类型的数组的排序;对象数组排序方法则。。。。。。。。。,这些方法提供了对象数组和泛型数组的排序算法的实现。

下文的讨论基于最后一种分类角度进行。本文首先来分析数据数组排序方法的实现。

数据数组排序方法: 
·代码:
    据数组排序方法提供了
byte,short,int,long,char,float,double 这7种基本数据类型的数组的排序实现。下面以int数组排序方法的实现为例,分析程序排序机理。
    以下为int数组对应的sort方法的代码实现:
代码-1
  /**
     * 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.
     *
     * @param a the array to be sorted
     */
    public static void sort(int[] a) {
        DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
    }


    方法实现很简单,直接调用DualPivotQuicksort类中的sort方法实现排序,该方法代码如下:  
代码-2
    /**
     * 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 (right - left < QUICKSORT_THRESHOLD) {
            sort(a, left, right, true);
            return;
        }

        /*
         * Index run[i] is the start of i-th run
         * (ascending or descending sequence).
         */
        int[] run = new int[MAX_RUN_COUNT + 1];
        int count = 0; run[0] = left;

        // Check if the array is nearly sorted
        for (int k = left; k < right; run[count] = k) {
            if (a[k] < a[k + 1]) { // ascending
                while (++k <= right && a[k - 1] <= a[k]);
            } else if (a[k] > a[k + 1]) { // descending
                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;
                }
            } else { // equal
                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.
             */
            if (++count == MAX_RUN_COUNT) {
                sort(a, left, right, true);
                return;
            }
        }

        // Check special cases
        // Implementation note: variable "right" is increased by 1.
        if (run[count] == right++) { // The last run contains one element
            run[++count] = right;
        } else if (count == 1) { // The array is already sorted
            return;
        }

        // 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
        int ao, bo;              // array offsets from 'left'
        int blen = right - left; // space needed for b
        if (work == null || workLen < blen || workBase + blen > work.length) {
            work = new int[blen];
            workBase = 0;
        }
        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;
            }
            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;
        }
    }

    以上代码对于归并排序和快速排序进行了改进,然后将这两种改进的算法结合起来,实现数组的排序,下文中,笔者首先
  • 23
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值