zoukankan      html  css  js  c++  java
  • Arrays.sort实现原理

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

    比较器的方式

    TimSort

     

    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;
    }
    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;
    }

     Collections.sort方法或者是Arrays.sort方法,底层实现都是TimSort实现的

    TimSort算法就是找到已经排好序数据的子序列,然后对剩余部分排序,然后合并起来

    纵有白头俱老意,奈何缘浅路芊芊.
  • 相关阅读:
    spring和设计模式
    Chrome插件下载网站图片
    MySql Illegal mix of collations 问题
    通过优化配置,提高MySql性能
    Windows下将Spring jar包部署为一个服务
    Apereo CAS增加登录方式。
    信息学竞赛C++基础教程
    关于codedecision和我本人
    信息学竞赛C++教程5.循环结构程序设计
    信息学竞赛C++教程3.分支结构程序设计
  • 原文地址:https://www.cnblogs.com/hanby/p/15037197.html
Copyright © 2011-2022 走看看