排序时小数组使用快排(插入排序):Use Quicksort on small arrays
之后考虑归并排序

Collection和Collections区别

java.util.Collection 是一个集合接口。它提供了对集合对象进行基本操作的通用接口方法。

java.util.Collections 是针对集合类的一个帮助类,他提供一系列静态方法实现对各种集合的搜索、排序、线程安全等操作。

然后还有混排(Shuffling)、反转(Reverse)、替换所有的元素(fill)、拷贝(copy)、返回Collections中最小元素(min)、返回Collections中最大元素(max)、返回指定源列表中最后一次出现指定目标列表的起始位置(lastIndexOfSubList)、返回指定源列表中第一次出现指定目标列表的起始位置(IndexOfSubList)、根据指定的距离循环移动指定列表中的元素(Rotate)

  1. 事实上Collections.sort方法底层就是调用的array.sort方法,而且不论是Collections.sort或者是Arrays.sort方法,

  2. 跟踪下源代码吧,首先我们写个demo 

    public static void main(String[] args) {
        List<String> strings = Arrays.asList("6", "1", "3", "1","2");
    
        Collections.sort(strings);//sort方法在这里
    
        for (String string : strings) {
    
            System.out.println(string);
        }
    }
    

    简单得不能再简单的方法了,让我们一步步跟踪

  3. OK,往下面看,发现collections.sort方法调用的list.sortArrays.sort 实现原理和 Collections.sort 实现原理

  4. 然后跟踪一下,list里面有个sort方法,但是list是一个接口,肯定是调用子类里面的实现,这里我们demo使用的是一个Arrays.asList方法,所以事实上我们的子类就是arraylist了。OK,看arraylist里面sort实现,选择第一个,为什么不选择第二个呢?(简单说就是用Arrays.sort创建的ArrayList对象)Arrays.sort 实现原理和 Collections.sort 实现原理

  5. 发现里面调用的Arrays.sort(a, c); a是list,c是一个比较器,我们来看一下这个方法 Arrays.sort 实现原理和 Collections.sort 实现原理

  6. 我们没有写比较器,所以用的第二项,LegacyMergeSort.userRequested这个bool值是什么呢? 
    跟踪这个值,我们发现有这样的一段定义:

     > Old merge sort implementation can be selected (for
      >  compatibility with broken comparators) using a system property.
      >  Cannot be a static boolean in the enclosing class due to
      >  circular dependencies. To be removed in a future release.
    
      反正是一种老的归并排序,不用管了现在默认是关的

     

  7. 我们走的是sort(a)这个方法,接着进入这个 Arrays.sort 实现原理和 Collections.sort 实现原理

  8. 接着看我们重要的sort方法
    static void sort(Object[] a, int lo, int hi, Object[] work, int workBase, int workLen) {
                     assert a != null && lo >= 0 && lo <= hi && hi <= a.length;
    
                     int nRemaining  = hi - lo;
                     if (nRemaining < 2)
                         return;  // array的大小为0或者1就不用排了
    
                     // 当数组大小小于MIN_MERGE(32)的时候,就用一个"mini-TimSort"的方法排序,jdk1.7新加
                     if (nRemaining < MIN_MERGE) {
                        //这个方法比较有意思,其实就是将我们最长的递减序列,找出来,然后倒过来
                         int initRunLen = countRunAndMakeAscending(a, lo, hi);
                         //长度小于32的时候,是使用binarySort的
                         binarySort(a, lo, hi, lo + initRunLen);
                         return;
                     }
                    //先扫描一次array,找到已经排好的序列,然后再用刚才的mini-TimSort,然后合并,这就是TimSort的核心思想
                     ComparableTimSort ts = new ComparableTimSort(a, work, workBase, workLen);
                     int minRun = minRunLength(nRemaining);
                     do {
                         // Identify next run
                         int runLen = countRunAndMakeAscending(a, lo, hi);
    
                         // If run is short, extend to min(minRun, nRemaining)
                         if (runLen < minRun) {
                             int force = nRemaining <= minRun ? nRemaining : minRun;
                             binarySort(a, lo, lo + force, lo + runLen);
                             runLen = force;
                         }
    
                         // Push run onto pending-run stack, and maybe merge
                         ts.pushRun(lo, runLen);
                         ts.mergeCollapse();
    
                         // Advance to find next run
                         lo += runLen;
                         nRemaining -= runLen;
                     } while (nRemaining != 0);
    
                     // Merge all remaining runs to complete sort
                     assert lo == hi;
                     ts.mergeForceCollapse();
                     assert ts.stackSize == 1;
             }
    

     

  9. 回到5,我们可以看到当我们写了比较器的时候就调用了TimSort.sort方法,源码如下
static <T> void sort(T[] a, int lo, int hi, Comparator<? super T> c,
                                  T[] work, int workBase, int workLen) {
                 assert c != null && a != null && lo >= 0 && lo <= hi && hi <= a.length;

                 int nRemaining  = hi - lo;
                 if (nRemaining < 2)
                     return;  // Arrays of size 0 and 1 are always sorted

                 // If array is small, do a "mini-TimSort" with no merges
                 if (nRemaining < MIN_MERGE) {
                     int initRunLen = countRunAndMakeAscending(a, lo, hi, c);
                     binarySort(a, lo, hi, lo + initRunLen, c);
                     return;
                 }

                 /**
                  * March over the array once, left to right, finding natural runs,
                  * extending short natural runs to minRun elements, and merging runs
                  * to maintain stack invariant.
                  */
           TimSort<T> ts = new TimSort<>(a, c, work, workBase, workLen);
                int minRun = minRunLength(nRemaining);
                do {
                    // Identify next run
                    int runLen = countRunAndMakeAscending(a, lo, hi, c);

                    // If run is short, extend to min(minRun, nRemaining)
                    if (runLen < minRun) {
                        int force = nRemaining <= minRun ? nRemaining : minRun;
                        binarySort(a, lo, lo + force, lo + runLen, c);
                        runLen = force;
                    }

                    // Push run onto pending-run stack, and maybe merge
                    ts.pushRun(lo, runLen);
                    ts.mergeCollapse();

                    // Advance to find next run
                    lo += runLen;
                    nRemaining -= runLen;
                } while (nRemaining != 0);

                // Merge all remaining runs to complete sort
                assert lo == hi;
                ts.mergeForceCollapse();
                assert ts.stackSize == 1;
      }

和上面的sort方法是一样的,其实也就是TimSort的源代码

不论是Collections.sort方法或者是Arrays.sort方法,底层实现都是TimSort实现的,这是jdk1.7新增的,以前是归并排序。TimSort算法就是找到已经排好序数据的子序列,然后对剩余部分排序,然后合并起来

 

Arrays.sort

事实上Collections.sort方法底层就是调用的array.sort方法

public static void sort(Object[] a) {
        if (LegacyMergeSort.userRequested)
            legacyMergeSort(a);
        else
            ComparableTimSort.sort(a, 0, a.length, null, 0, 0);
    }
//void java.util.ComparableTimSort.sort()
static void sort(Object[] a, int lo, int hi, Object[] work, int workBase, int workLen) {
        assert a != null && lo >= 0 && lo <= hi && hi <= a.length;

        int nRemaining  = hi - lo;
        if (nRemaining < 2)
            return;  // Arrays of size 0 and 1 are always sorted

        // If array is small, do a "mini-TimSort" with no merges
        if (nRemaining < MIN_MERGE) {
            int initRunLen = countRunAndMakeAscending(a, lo, hi);
            binarySort(a, lo, hi, lo + initRunLen);
            return;
        }

legacyMergeSort(a):归并排序
ComparableTimSort.sort():Timsort排序

备注:

Timsort排序是结合了合并排序(merge sort)和插入排序(insertion sort)而得出的排序算法。(参考:Timsort原理介绍

Timsort的核心过程:

TimSort 算法为了减少对升序部分的回溯和对降序部分的性能倒退,将输入按其升序和降序特点进行了分区。排序的输入的单位不是一个个单独的数字,而是一个个的块-分区。其中每一个分区叫一个run。针对这些 run 序列,每次拿一个 run 出来按规则进行合并。每次合并会将两个 run合并成一个 run。合并的结果保存到栈中。合并直到消耗掉所有的 run,这时将栈上剩余的 run合并到只剩一个 run 为止。这时这个仅剩的 run 便是排好序的结果。

综上述过程,Timsort算法的过程包括

(0)如何数组长度小于某个值,直接用二分插入排序算法

(1)找到各个run,并入栈

(2)按规则合并run

 

 

 

相关文章: