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算法就是找到已经排好序数据的子序列,然后对剩余部分排序,然后合并起来

    纵有白头俱老意,奈何缘浅路芊芊.
  • 相关阅读:
    ExtJS4学习笔记二--表单控件相关
    Js中replace()的用法
    浅析轮询(Polling)和推送(LongPolling)服务
    ExtJS4学习笔记五--面板使用
    ExtJS4学习笔记四--图片上传
    spring MVC
    ExtJS4学习笔记三--远程访问数据源示例
    Struts 2
    ExtJs4学习笔记一--基础知识
    URL编码规则
  • 原文地址:https://www.cnblogs.com/hanby/p/15037197.html
Copyright © 2011-2022 走看看