TimSort 源码阅读笔记

TimSort 源码阅读笔记

目录

算法介绍

TimeSort原理介绍

源码阅读

TimSort

/**
 * This is the minimum sized sequence that will be merged.  Shorter
 * sequences will be lengthened by calling binarySort.  If the entire
 * array is less than this length, no merges will be performed.
 * 这是将要合并的最小大小的序列。 较短的序列将通过调用 binarySort 来加长。
 * 如果整个数组小于此长度,将不执行合并。
 * This constant should be a power of two.  It was 64 in Tim Peter's C
 * implementation, but 32 was empirically determined to work better in
 * this implementation.  In the unlikely event that you set this constant
 * to be a number that's not a power of two, you'll need to change the
 * {@link #minRunLength} computation.
 * 该常数应为 2 的幂。Tim Peter 的 C 实现中为 64,但是凭经验确定 32 在该实现
 * 中可以更好地工作。万一将此常数设置为不是 2 的幂的数字,则需要更改 
 * {@link #minRunLength} 计算。
 * If you decrease this constant, you must change the stackLen
 * computation in the TimSort constructor, or you risk an
 * ArrayOutOfBounds exception.  See listsort.txt for a discussion
 * of the minimum stack length required as a function of the length
 * of the array being sorted and the minimum merge sequence length.
 * 如果减小此常数,则必须在 TimSort 构造函数中更改 stackLen 计算,否则可能会
 * 引发 ArrayOutOfBounds 异常。请参阅 listsort.txt,以获取所需的最小堆栈长度
 * (取决于要排序的数组的长度和最小合并序列长度)的讨论。
 */
private static final int MIN_MERGE = 32;

/**
 * Maximum initial size of tmp array, which is used for merging.  The array
 * can grow to accommodate demand.
 * tmp 数组的最大初始大小,用于合并。 阵列可以增长以适应需求。
 * Unlike Tim's original C version, we do not allocate this much storage
 * when sorting smaller arrays.  This change was required for performance.
 * 与 Tim 的原始 C 版本不同,在对较小的数组进行排序时,我们不会分配太多存储空间。
 * 性能需要进行此更改。
 */
private static final int INITIAL_TMP_STORAGE_LENGTH = 256;

/**
 * Temp storage for merges. A workspace array may optionally be
 * provided in constructor, and if so will be used as long as it
 * is big enough.
 * 用于合并的临时存储。 可以选择在构造函数中提供一个工作区数组,如果足够大,则将使用它。
 */
private T[] tmp;
private int tmpBase; // base of tmp array slice : tmp 数组切片的基础
private int tmpLen;  // length of tmp array slice : tmp 数组切片的长度

/**
 * A stack of pending runs yet to be merged.  Run i starts at
 * address base[i] and extends for len[i] elements.  It's always
 * true (so long as the indices are in bounds) that:
 *
 *     runBase[i] + runLen[i] == runBase[i + 1]
 *
 * so we could cut the storage for this, but it's a minor amount,
 * and keeping all the info explicit simplifies the code.
 *
 * 栈中待归并的run的数量。一个run i的范围从runBase[i]开始,一直延续到runLen[i]。
 * 下面这个根据前一个run的结尾总是下一个run的开头。
 * 所以下面的等式总是成立:
 * runBase[i] + runLen[i] == runBase[i+1];
 */
private int stackSize = 0;  // Number of pending runs on stack : 堆栈上待处理的运行次数
private final int[] runBase;
private final int[] runLen;

/**
 * Sorts the given range, using the given workspace array slice
 * for temp storage when possible. This method is designed to be
 * invoked from public methods (in class Arrays) after performing
 * any necessary array bounds checks and expanding parameters into
 * the required forms.
 * 在可能的情况下,使用给定的工作空间数组切片对临时存储区进行排序。此方法
 * 设计为在执行任何必要的数组边界检查并将参数扩展为所需形式之后,从公共方
 * 法(在 Arrays 类中)调用。
 *
 * @param a the array to be sorted
 * @param lo the index of the first element, inclusive, to be sorted
 * 要排序数组的第一个元素的索引,包含
 * @param hi the index of the last element, exclusive, to be sorted
 * 被排序数组的最后一个元素的索引,不包含
 * @param c the comparator to use
 * @param work a workspace array (slice)
 * 工作区数组(切片)
 * @param workBase origin of usable space in work array
 * 工作阵列中可用空间的源数组
 * @param workLen usable size of work array
 * 工作数组的可用大小
 * @since 1.8
 */
static <T> void sort(T[] a, int lo, int hi, Comparator<? super T> c,
                     T[] work, int workBase, int workLen) {
    // assert 断言:如果 [ boolean 表达式 ]为 true,则程序继续执行。如果为 false,则程序抛出 AssertionError,并终止执行。
    // 对数据进行合法性校验
    assert c != null && a != null && lo >= 0 && lo <= hi && hi <= a.length;

    // 待排序元素的剩余数量
    int nRemaining  = hi - lo;
    if (nRemaining < 2)
        // Arrays of size 0 and 1 are always sorted
        // 大小为 0 和 1 的数组始终有序
        return;  

    // If array is small, do a "mini-TimSort" with no merges
    // 如果数组很小,执行不使用归并排序的方法 "mini-TimSort"
    if (nRemaining < MIN_MERGE) {
        // 计算数组前部分有序的最大长度,并无论前半部分是升序还是降序,都转为升序
        // initRunLen 最小为 1
        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.
     * 从左到右,遍历一边数组。找出自然排好序的序列(natural run),把短的自然升序
     * 序列通过二叉查找排序扩展到 minRun 长度的升序序列。最后合并栈中的所有升序序列,
     * 保证规则不变。
     */
    // 创建一个 TimSort 实例来维护正在进行的排序状态
    TimSort<T> ts = new TimSort<>(a, c, work, workBase, workLen);
     // 主要将数组分为一个个的 minRun,最后在进行合并,如果长度为 2 的 n 次幂,minRun 为 32,
     // 否则为 16 - 32 之间的数.
    int minRun = minRunLength(nRemaining);
    do {
        // Identify next run : 确定下一次运行
        // 找到下一段 a 中已经有序的元素个数
        int runLen = countRunAndMakeAscending(a, lo, hi, c);

        // If run is short, extend to min(minRun, nRemaining)
        // 果有序个数小于上面的 minRun,则扩展到 min(minRun,nRemaining)
        if (runLen < minRun) {
            int force = nRemaining <= minRun ? nRemaining : minRun;
            // 通过二分排序扩展有序数组
            binarySort(a, lo, lo + force, lo + runLen, c);
            // 跟新下一段 a 中已经有序的元素个数
            runLen = force;
        }

        // Push run onto pending-run stack, and maybe merge
        // 把已经排好序的数列压入栈中,检查是不是需要合并
        ts.pushRun(lo, runLen);
        // 检查栈中待归并的升序序列
        ts.mergeCollapse();

        // Advance to find next run
        // 把指针后移 runLen距离,准备开始下一轮片段的排序
        lo += runLen;
        // 剩下待排序的数量相应的减少 runLen
        nRemaining -= runLen;
    } while (nRemaining != 0);

    // Merge all remaining runs to complete sort
    // 合并所有剩余运行以完成排序
    assert lo == hi;
    ts.mergeForceCollapse();
    assert ts.stackSize == 1;
}

/**
 * Returns the length of the run beginning at the specified position in
 * the specified array and reverses the run if it is descending (ensuring
 * that the run will always be ascending when the method returns).
 * 返回从指定数组中指定位置开始的运行长度,如果运行是递减的,则将其反转(确保方法返回时运行将始终以升序)。
 * A run is the longest ascending sequence with:
 * 运行是最长的升序序列,其中:
 *    a[lo] <= a[lo + 1] <= a[lo + 2] <= ...
 *
 * or the longest descending sequence with:
 * 或最长的降序序列:
 *    a[lo] >  a[lo + 1] >  a[lo + 2] >  ...
 *
 * For its intended use in a stable mergesort, the strictness of the
 * definition of "descending" is needed so that the call can safely
 * reverse a descending sequence without violating stability.
 * 为了在稳定的 mergesort 中预期使用,需要严格定义“降序”,以便调用可以安全地反转降序,而不会破坏稳定性。
 * @param a the array in which a run is to be counted and possibly reversed
 * @param lo index of the first element in the run
 * @param hi index after the last element that may be contained in the run.
          It is required that {@code lo < hi}.
 * @param c the comparator to used for the sort
 * @return  the length of the run beginning at the specified position in
 *          the specified array
 */
private static <T> int countRunAndMakeAscending(T[] a, int lo, int hi,
                                                Comparator<? super T> c) {
    assert lo < hi;
    int runHi = lo + 1;
    // 运行序列为 1,不做后续处理,返回长度 1
    if (runHi == hi)
        return 1;

    // Find end of run, and reverse range if descending
    // 查找运行结束,如果是降序则反转范围
    // 判断数组前两元素是降序还是升序,用来决定数组前部分进行是升序还是降序处理
    if (c.compare(a[runHi++], a[lo]) < 0) { // Descending : 降序
        // 获取最大的倒序部分数组索引
        while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0)
            runHi++;
        // 对 lo -> runHi 部分降序的数组进行反转为升序
        reverseRange(a, lo, runHi);
    } else {                              // Ascending : 升序
         // 获取最大的升序部分数组索引
        while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0)
            runHi++;
    }
    
    // 返回刚刚获取到的有序(升序)部分的数组长度
    return runHi - lo;
}

/**
 * Reverse the specified range of the specified array.
 *
 * @param a the array in which a range is to be reversed
 * @param lo the index of the first element in the range to be reversed
 * @param hi the index after the last element in the range to be reversed
 * 范围内最后一个元素之后的索引(也就是说反转操作不包含 hi 索引)
 */
private static void reverseRange(Object[] a, int lo, int hi) {
    // 不包含 hi,所以进行索引回退
    hi--;
    // 首尾对应元素交换,进行数组反转操作
    while (lo < hi) {
        // 从头部获取当前未反转的元素
        Object t = a[lo];
        // 将当前头部未反转元素变更为当前尾部未反转的元素
        a[lo++] = a[hi];
        // 将当前尾部未反转元素变更为缓存的当前头部已反转的元素
        a[hi--] = t;
    }
}

/**
 * Sorts the specified portion of the specified array using a binary
 * insertion sort.  This is the best method for sorting small numbers
 * of elements.  It requires O(n log n) compares, but O(n^2) data
 * movement (worst case).
 * 使用二分制插入排序对指定数组的指定部分进行排序。这是对少量元素进行排序的
 * 最佳方法。它需要O(n log n)进行比较,但是需要O(n ^ 2)数据移动(最坏的情况)。
 * If the initial part of the specified range is already sorted,
 * this method can take advantage of it: the method assumes that the
 * elements from index {@code lo}, inclusive, to {@code start},
 * exclusive are already sorted.
 * 如果指定范围的起始部分已被排序,则此方法可以利用它:该方法假定从索引{@code lo}
 *(包括)到{@code start}(不包括)的元素已经被排序。
 * @param a the array in which a range is to be sorted
 * @param lo the index of the first element in the range to be sorted
 * @param hi the index after the last element in the range to be sorted
 * @param start the index of the first element in the range that is
 *        not already known to be sorted ({@code lo <= start <= hi})
 * 未知排序范围内第一个元素的索引({@code lo <= start <= hi})
 */
@SuppressWarnings({"fallthrough", "rawtypes", "unchecked"})
private static void binarySort(Object[] a, int lo, int hi, int start) {
    // 边界合法性校验
    assert lo <= start && start <= hi;
    // 现在 a 已经分为两部分“已排序区”和“待排序区域”,start 就是待排序区的起始索引
    // 根据方法调用链的上一个方法可知,start 最小为 lo + 1,所以到 start == lo 时,对 start 进行调整
    // 为什么不直接抛出异常?可能其他方法调用此方法时会出现 start == lo 的情况,
    // 这样就将第一个元素划分为一个区,所以对 start++
    if (start == lo)
        start++;
    // 实现排序的核心代码
    // 思想就是:每次取一个未排序区的元素,使用二分查找在“已排序区”找到这个未排序数据的正确位置进行插入   
    for ( ; start < hi; start++) {
        // 获取当前“未排序区域”首个元素
        Comparable pivot = (Comparable) a[start];

        // Set left (and right) to the index where a[start] (pivot) belongs
        // 将左(和右)设置为a [start](枢轴)所属的索引
        // 简单的理解就是,left -> right  - 1 范围是已排序区域
        int left = lo;
        int right = start;
        assert left <= right;
        /*
         *   pivot >= all in [lo, left).
         *   pivot <  all in [right, start).
         */
         // 使用二分查找在“已排序区”找当前未排序元素的正确位置
        while (left < right) {
            int mid = (left + right) >>> 1;
            if (pivot.compareTo(a[mid]) < 0)
                right = mid;
            else
                left = mid + 1;
        }
        // left 和 right 相等的索引就是未排序元素的正确位置
        assert left == right;

        /*
         * The invariants still hold: pivot >= all in [lo, left) and
         * pivot < all in [left, start), so pivot belongs at left.  Note
         * that if there are elements equal to pivot, left points to the
         * first slot after them -- that's why this sort is stable.
         * Slide elements over to make room for pivot.
         * 不变量仍然成立:pivot> = all in [lo,left),pivot <all in [left,start),
         * 因此,pivot属于左侧。请注意,如果有等于pivot的元素,则左侧指向它们之后的
         * 第一个插槽,这就是这种排序稳定的原因。将元素滑到上方以留出旋转的空间。
         */
        int n = start - left;  // The number of elements to move : 要移动的元素数
        // Switch is just an optimization for arraycopy in default case
        // Switch 只是默认情况下对 arraycopy 的优化
        // 注意到 case 2: 没有 break
        // 这样做的目的是,如果待插入的元素的位置在“已排序区”的倒数第二或者倒数第一,就使用
        // 赋值移动,使用 switch 可以巧妙的实现两种情况
        switch (n) {
            case 2:  a[left + 2] = a[left + 1];
            case 1:  a[left + 1] = a[left];
                     break;
            // 其他情况则使用拷贝实现元素后移 n 个位置         
            default: System.arraycopy(a, left, a, left + 1, n);
        }
        // 将待排序元素赋值到正确位置
        a[left] = pivot;
    }
}

/**
 * Creates a TimSort instance to maintain the state of an ongoing sort.
 * 创建一个TimSort实例来维护正在进行的排序状态。
 * @param a the array to be sorted
 * @param c the comparator to determine the order of the sort
 * @param work a workspace array (slice)
 * 工作区数组(切片)
 * @param workBase origin of usable space in work array
 * 工作数组中可用空间的源数组大小
 * @param workLen usable size of work array
 * 工作数组的可用大小
 */
private TimSort(T[] a, Comparator<? super T> c, T[] work, int workBase, int workLen) {
    this.a = a;
    this.c = c;

    // Allocate temp storage (which may be increased later if necessary)
    // 分配临时存储(如有必要,可在以后增加)   
    int len = a.length;
    // 当 len < 2 * 256,tlen 大小为 1/2 * 256,否则 tlen 大小为 256
    int tlen = (len < 2 * INITIAL_TMP_STORAGE_LENGTH) ?
        len >>> 1 : INITIAL_TMP_STORAGE_LENGTH;
    // 如果 下面条件有一个为 true 就对 tmp 数组进行创建,否则就将传入的相关参数赋值给 tmp    
    if (work == null || workLen < tlen || workBase + tlen > work.length) {
        @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
        // 通过反射根据 a 数组中元素类型,创建大小为 tlen 的 newArray 数组 
        T[] newArray = (T[])java.lang.reflect.Array.newInstance
            (a.getClass().getComponentType(), tlen);
        tmp = newArray;
        tmpBase = 0;
        tmpLen = tlen;
    }
    else {
        tmp = work;
        tmpBase = workBase;
        tmpLen = workLen;
    }

    /*
     * Allocate runs-to-be-merged stack (which cannot be expanded).  The
     * stack length requirements are described in listsort.txt.  The C
     * version always uses the same stack length (85), but this was
     * measured to be too expensive when sorting "mid-sized" arrays (e.g.,
     * 100 elements) in Java.  Therefore, we use smaller (but sufficiently
     * large) stack lengths for smaller arrays.  The "magic numbers" in the
     * computation below must be changed if MIN_MERGE is decreased.  See
     * the MIN_MERGE declaration above for more information.
     * The maximum value of 49 allows for an array up to length
     * Integer.MAX_VALUE-4, if array is filled by the worst case stack size
     * increasing scenario. More explanations are given in section 4 of:
     * http://envisage-project.eu/wp-content/uploads/2015/02/sorting.pdf
     * 这里是分配储存 run 的栈的空间,它不能在运行时扩展。
     * C 语言版本中的栈一直使用固定值 85,但这样对一些中小数组来说有些浪费资源。所以,
     * 这个版本我们使用了相对较小容量的栈。
     * 在 MIN_MERGE 减小的时候,这些‘魔法数’可能面临数组越界的风险。
     */
    int stackLen = (len <    120  ?  5 :
                    len <   1542  ? 10 :
                    len < 119151  ? 24 : 49);
    runBase = new int[stackLen];
    runLen = new int[stackLen];
}
    
/**
 * Returns the minimum acceptable run length for an array of the specified
 * length. Natural runs shorter than this will be extended with
 * {@link #binarySort}.
 * 返回参与合并的最小长度,如果自然排序的长度,小于此长度,那么就通过二分查找排序扩展到
 * 此长度。{@link #binarySort}.
 * Roughly speaking, the computation is:
 * 粗略的讲,计算结果是这样的:
 *  If n < MIN_MERGE, return n (it's too small to bother with fancy stuff).
 *  如果 n < MIN_MERGE, 直接返回 n。(太小了,不值得做复杂的操作);
 *  Else if n is an exact power of 2, return MIN_MERGE/2.
 *  如果 n 正好是2的幂,返回 n / 2;
 *  Else return an int k, MIN_MERGE/2 <= k <= MIN_MERGE, such that n/k
 *   is close to, but strictly less than, an exact power of 2.
 *  其它情况下 返回一个数 k,满足 MIN_MERGE/2 <= k <= MIN_MERGE, 这样结果就能保证 n/k 
 *   非常接近但小于一个2的幂 
 * For the rationale, see listsort.txt.
 *
 * @param n the length of the array to be sorted
 * @return the length of the minimum run to be merged
 */
private static int minRunLength(int n) {
    assert n >= 0;
    // 如果不是 2 的幂就会为 1
    int r = 0;    
    while (n >= MIN_MERGE) {
        r |= (n & 1);
        n >>= 1;
    }
    return n + r;
}    

/**
 * Pushes the specified run onto the pending-run stack.
 * 将指定的升序序列压入等待合并的栈中
 * @param runBase index of the first element in the run
 * @param runLen  the number of elements in the run
 */
private void pushRun(int runBase, int runLen) {
    this.runBase[stackSize] = runBase;
    this.runLen[stackSize] = runLen;
    stackSize++;
}

/**
 * Examines the stack of runs waiting to be merged and merges adjacent runs
 * until the stack invariants are reestablished:
 * 检查栈中待归并的升序序列,如果他们不满足下列条件就把相邻的两个序列合并,
 * 直到他们满足下面的条件
 *     1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1]
 *     2. runLen[i - 2] > runLen[i - 1]
 * This method is called each time a new run is pushed onto the stack,
 * so the invariants are guaranteed to hold for i < stackSize upon
 * entry to the method.
 * 每次添加新序列到栈中的时候都会执行一次这个操作。所以栈中的需要满足的条件
 * 需要靠调用这个方法来维护。
 */
private void mergeCollapse() {
    // 最少都得有两个块,如果没有,则退出.
    while (stackSize > 1) {
        // stackSize为块的数量,-2 相当与倒数第二个块
        int n = stackSize - 2;
         // 倒数第三个 Run 块大小小于后面两个块的大小和
        if (n > 0 && runLen[n-1] <= runLen[n] + runLen[n+1]) {
            // 如果倒数第三个块比倒一块的大小小,就从倒数第三个块进行合并
            if (runLen[n - 1] < runLen[n + 1])
                n--;
            mergeAt(n);
        } 
        // 第一个块大小小于第二个块大小,就合并这两个
        else if (runLen[n] <= runLen[n + 1]) {
            mergeAt(n);
        } 
        // 否则什么都不做 
        else {
            break; // Invariant is established
        }
    }
}

/**
 * Merges the two runs at stack indices i and i+1.  Run i must be
 * the penultimate or antepenultimate run on the stack.  In other words,
 * i must be equal to stackSize-2 or stackSize-3.
 * 合并在栈中位于 i 和 i + 1 的两个相邻的升序序列。i 必须为从栈顶数,第二和第三个元素。
 * 换句话说 i == stackSize - 2 || i == stackSize - 3
 *
 * @param i stack index of the first of the two runs to merge
 * 待合并的第一个序列所在的位置
 */
private void mergeAt(int i) {
    // 校验
    assert stackSize >= 2;
    assert i >= 0;
    assert i == stackSize - 2 || i == stackSize - 3;
    
    // 初始化数据,准备合并时使用
    int base1 = runBase[i];
    int len1 = runLen[i];
    int base2 = runBase[i + 1];
    int len2 = runLen[i + 1];
    assert len1 > 0 && len2 > 0;
    assert base1 + len1 == base2;

    /*
     * Record the length of the combined runs; if i is the 3rd-last
     * run now, also slide over the last run (which isn't involved
     * in this merge).  The current run (i+1) goes away in any case.
     * 记录合并后的序列的长度;如果i == stackSize - 3 就把最后一个序列的信息
     * 往前移一位,因为本次合并不关它的事。i + 1 对应的序列被合并到i序列中了,所以
     * i + 1 数列可以消失了
     */
    runLen[i] = len1 + len2;
    if (i == stackSize - 3) {
        runBase[i + 1] = runBase[i + 2];
        runLen[i + 1] = runLen[i + 2];
    }
    // i + 1 消失了,所以长度也减下来了
    stackSize--;

    /*
     * Find where the first element of run2 goes in run1. Prior elements
     * in run1 can be ignored (because they're already in place).
     * 找出第二个序列的首个元素可以插入到第一个序列的什么位置,因为在此位置之前的序列已经就位了。
     * 它们可以被忽略,不参加归并。
     */
    int k = gallopRight(a[base2], a, base1, len1, 0, c);
    assert k >= 0;
    // 因为要忽略前半部分元素,所以起点和长度相应的变化
    base1 += k;
    len1 -= k;
    // 如果序列 2 的首个元素要插入到序列 1 的后面,那就直接结束了,
    // 因为序列 2 在数组中的位置本来就在序列 1 后面,也就是整个范围本来就是有序的!
    if (len1 == 0)
        return;

    /*
     * Find where the last element of run1 goes in run2. Subsequent elements
     * in run2 can be ignored (because they're already in place).
     */
    len2 = gallopLeft(a[base1 + len1 - 1], a, base2, len2, len2 - 1, c);
    assert len2 >= 0;
    if (len2 == 0)
        return;

    // Merge remaining runs, using tmp array with min(len1, len2) elements
    if (len1 <= len2)
        mergeLo(base1, len1, base2, len2);
    else
        mergeHi(base1, len1, base2, len2);
}

/**
 * Merges all runs on the stack until only one remains.  This method is
 * called once, to complete the sort.
 */
private void mergeForceCollapse() {
    while (stackSize > 1) {
        int n = stackSize - 2;
        if (n > 0 && runLen[n - 1] < runLen[n + 1])
            n--;
        mergeAt(n);
    }
}

/**
 * Locates the position at which to insert the specified key into the
 * specified sorted range; if the range contains an element equal to key,
 * returns the index of the leftmost equal element.
 * 在一个序列中,将一个指定的key,从左往右查找它应当插入的位置;如果序列中存在
 * 与key相同的值(一个或者多个),那返回这些值中最左边的位置。
 * @param key the key whose insertion point to search for
 * 准备插入的 key
 * @param a the array in which to search
 * 参与排序的数组
 * @param base the index of the first element in the range
 * 序列范围的第一个元素的位置
 * @param len the length of the range; must be > 0
 * 整个长度的长度,一定有 len > 0
 * @param hint the index at which to begin the search, 0 <= hint < n.
 *     The closer hint is to the result, the faster this method will run.
 * 开始查找的位置,有 0 <= hint <= len;越接近结果查找越快
 * @param c the comparator used to order the range, and to search
 * @return the int k,  0 <= k <= n such that a[b + k - 1] < key <= a[b + k],
 *    pretending that a[b - 1] is minus infinity and a[b + n] is infinity.
 *    In other words, key belongs at index b + k; or in other words,
 *    the first k elements of a should precede key, and the last n - k
 *    should follow it.
 */
private static <T> int gallopLeft(T key, T[] a, int base, int len, int hint,
                                  Comparator<? super T> c) {
    assert len > 0 && hint >= 0 && hint < len;
    int lastOfs = 0;
    int ofs = 1;
    if (c.compare(key, a[base + hint]) > 0) {
        // Gallop right until a[base+hint+lastOfs] < key <= a[base+hint+ofs]
        // 遍历右边,直到 a[base+hint+lastOfs] < key <= a[base+hint+ofs]
        int maxOfs = len - hint;
        while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) > 0) {
            lastOfs = ofs;
            ofs = (ofs << 1) + 1;
            if (ofs <= 0)   // int overflow
                ofs = maxOfs;
        }
        if (ofs > maxOfs)
            ofs = maxOfs;
        // 最终的ofs是这样确定的,
        // 满足条件 a[base+hint+lastOfs] < key <= a[base+hint+ofs] 的一组
        // ofs:     1   3   7  15  31  63 2^n-1 ... maxOfs
        // lastOfs: 0   1   3   7  15  31 2^(n-1)-1  < ofs    
            
        // Make offsets relative to base
        // 因为目前的 offset 是相对 hint 的,所以做相对变换
        lastOfs += hint;
        ofs += hint;
    } else { // key <= a[base + hint]
        // Gallop left until a[base+hint-ofs] < key <= a[base+hint-lastOfs]
        // 遍历左边,直到 [base+hint-ofs] < key <= a[base+hint-lastOfs]
        final int maxOfs = hint + 1;
        while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) <= 0) {
            lastOfs = ofs;
            ofs = (ofs << 1) + 1;
            if (ofs <= 0)   // int overflow
                ofs = maxOfs;
        }
        if (ofs > maxOfs)
            ofs = maxOfs;
        // 确定ofs的过程与上面相同
        // ofs:     1   3   7  15  31  63 2^n-1 ... maxOfs
        // lastOfs: 0   1   3   7  15  31 2^(n-1)-1  < ofs

        // Make offsets relative to base
        // 相对于基准偏移
        int tmp = lastOfs;
        lastOfs = hint - ofs;
        ofs = hint - tmp;
    }
    assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;

    /*
     * Now a[base+lastOfs] < key <= a[base+ofs], so key belongs somewhere
     * to the right of lastOfs but no farther right than ofs.  Do a binary
     * search, with invariant a[base + lastOfs - 1] < key <= a[base + ofs].
     * 现在的情况是 a[base+lastOfs] < key <= a[base+ofs], 所以,key 应当在 lastOfs 的
     * 右边,又不超过 ofs。在 base+lastOfs-1 到 base+ofs 范围内做一次二叉查找。
     */
    lastOfs++;
    while (lastOfs < ofs) {
        int m = lastOfs + ((ofs - lastOfs) >>> 1);

        if (c.compare(key, a[base + m]) > 0)
            lastOfs = m + 1;  // a[base + m] < key
        else
            ofs = m;          // key <= a[base + m]
    }
    assert lastOfs == ofs;    // so a[base + ofs - 1] < key <= a[base + ofs]
    return ofs;
}

/**
 * Like gallopLeft, except that if the range contains an element equal to
 * key, gallopRight returns the index after the rightmost equal element.
 * 与 gallopLeft 相似,不同的是如果发现 key 的值与某些元素相等,那返回这些值最
 * 后一个元素的位置的后一个位置
 * @param key the key whose insertion point to search for
 * @param a the array in which to search
 * @param base the index of the first element in the range
 * @param len the length of the range; must be > 0
 * @param hint the index at which to begin the search, 0 <= hint < n.
 *     The closer hint is to the result, the faster this method will run.
 * @param c the comparator used to order the range, and to search
 * @return the int k,  0 <= k <= n such that a[b + k - 1] <= key < a[b + k]
 */
private static <T> int gallopRight(T key, T[] a, int base, int len,
                                   int hint, Comparator<? super T> c) {
    assert len > 0 && hint >= 0 && hint < len;

    int ofs = 1;
    int lastOfs = 0;
    if (c.compare(key, a[base + hint]) < 0) {
        // Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs]
        int maxOfs = hint + 1;
        while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) < 0) {
            lastOfs = ofs;
            ofs = (ofs << 1) + 1;
            if (ofs <= 0)   // int overflow
                ofs = maxOfs;
        }
        if (ofs > maxOfs)
            ofs = maxOfs;

        // Make offsets relative to b
        int tmp = lastOfs;
        lastOfs = hint - ofs;
        ofs = hint - tmp;
    } else { // a[b + hint] <= key
        // Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs]
        int maxOfs = len - hint;
        while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) >= 0) {
            lastOfs = ofs;
            ofs = (ofs << 1) + 1;
            if (ofs <= 0)   // int overflow
                ofs = maxOfs;
        }
        if (ofs > maxOfs)
            ofs = maxOfs;

        // Make offsets relative to b
        lastOfs += hint;
        ofs += hint;
    }
    assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;

    /*
     * Now a[b + lastOfs] <= key < a[b + ofs], so key belongs somewhere to
     * the right of lastOfs but no farther right than ofs.  Do a binary
     * search, with invariant a[b + lastOfs - 1] <= key < a[b + ofs].
     */
    lastOfs++;
    while (lastOfs < ofs) {
        int m = lastOfs + ((ofs - lastOfs) >>> 1);

        if (c.compare(key, a[base + m]) < 0)
            ofs = m;          // key < a[b + m]
        else
            lastOfs = m + 1;  // a[b + m] <= key
    }
    assert lastOfs == ofs;    // so a[b + ofs - 1] <= key < a[b + ofs]
    return ofs;
}

/**
 * Merges two adjacent runs in place, in a stable fashion.  The first
 * element of the first run must be greater than the first element of the
 * second run (a[base1] > a[base2]), and the last element of the first run
 * (a[base1 + len1-1]) must be greater than all elements of the second run.
 * 使用固定空间合并两个相邻的有序序列,保持数组的稳定性。
 * 使用本方法之前保证第一个序列的首个元素大于第二个序列的首个元素;第一个序列的末尾元素
 * 大于第二个序列的所有元素
 * For performance, this method should be called only when len1 <= len2;
 * its twin, mergeHi should be called if len1 >= len2.  (Either method
 * may be called if len1 == len2.)
 * 为了性能,这个方法在len1 <= len2的时候调用;它的姐妹方法mergeHi应该在len1 >= len2
 * 的时候调用。len1==len2的时候随便调用哪个都可以
 * @param base1 index of first element in first run to be merged
 * @param len1  length of first run to be merged (must be > 0)
 * @param base2 index of first element in second run to be merged
 *        (must be aBase + aLen)
 * @param len2  length of second run to be merged (must be > 0)
 */
private void mergeLo(int base1, int len1, int base2, int len2) {
    assert len1 > 0 && len2 > 0 && base1 + len1 == base2;

    // Copy first run into temp array
    // 将第一个序列放到临时数组中
    T[] a = this.a; // For performance
    T[] tmp = ensureCapacity(len1);
    int cursor1 = tmpBase; // Indexes into tmp array : 临时数组指针
    int cursor2 = base2;   // Indexes int a : 序列 2 的指针,参与归并的另一个序列
    int dest = base1;      // Indexes int a : 保存结果的指针
    System.arraycopy(a, base1, tmp, cursor1, len1);

    // Move first element of second run and deal with degenerate cases
     // 这里先把第二个序列的首个元素,移动到结果序列中的位置,然后处理那些不需要归并的情况
    a[dest++] = a[cursor2++];
    // 序列 2只有一个元素的情况,把它移动到指定位置之后,剩下的临时数组
    // 中的所有序列 1 的元素全部 copy 到后面
    if (--len2 == 0) {
        System.arraycopy(tmp, cursor1, a, dest, len1);
        return;
    }
    // 序列1只有一个元素的情况,把它移动到最后一个位置,为了不覆盖,先把序列2中的元素
    // 全部移走。这个是因为序列1中的最后一个元素比序列2中的所有元素都大,这是该方法执行的条件
    if (len1 == 1) {
        System.arraycopy(a, cursor2, a, dest, len2);
        a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge : 运行 1 的最后一个 elt 到合并结束
        return;
    }

    Comparator<? super T> c = this.c;  // Use local variable for performance : 使用局部变量来提高性能
    int minGallop = this.minGallop;    //  "    "       "     "      "
outer:
    while (true) {
        /*
         * 这里加了两个值来记录一个序列连续比另外一个大的次数,根据此信息,可以做出一些优化
         */
        int count1 = 0; // Number of times in a row that first run won : 序列 1 连续 比序列 2 大多少次
        int count2 = 0; // Number of times in a row that second run won : 序列 2 连续 比序列 1 大多少次

        /**
         * Do the straightforward thing until (if ever) one run starts
         * winning consistently.
         * 这里是直接的归并算法的合并的部分,这里会统计 count1 和 count2, 如果其中一个大于一个阈值,就会跳出循环
         */
        do {
            assert len1 > 1 && len2 > 0;
            if (c.compare(a[cursor2], tmp[cursor1]) < 0) {
                a[dest++] = a[cursor2++];
                count2++;
                count1 = 0;
                // 序列 2 没有元素了就跳出整次合并
                if (--len2 == 0)
                    break outer;
            } else {
                a[dest++] = tmp[cursor1++];
                count1++;
                count2 = 0;
                // 如果序列 1 只剩下最后一个元素了就可以跳出循环
                if (--len1 == 1)
                    break outer;
            }
       /**
        * 这个判断相当于 count1 < minGallop && count2 <minGallop
        * 因为 count1 和 count2 总有一个为 0
        */
        } while ((count1 | count2) < minGallop);

        /**
         * One run is winning so consistently that galloping may be a
         * huge win. So try that, and continue galloping until (if ever)
         * neither run appears to be winning consistently anymore.
         * 执行到这里的话,一个序列会连续的的比另一个序列大,那么这种连续性可能持续的
         * 更长。那么我们就按照这个逻辑试一试。直到这种连续性被打破。根据找到的长度,
         * 直接连续的 copy 就可以了,这样可以提高 copy 的效率。
         */
        do {
            assert len1 > 1 && len2 > 0;
            count1 = gallopRight(a[cursor2], tmp, cursor1, len1, 0, c);
            if (count1 != 0) {
                System.arraycopy(tmp, cursor1, a, dest, count1);
                dest += count1;
                cursor1 += count1;
                len1 -= count1;
                // 结尾处理退化的序列
                if (len1 <= 1) // len1 == 1 || len1 == 0
                    break outer;
            }
            a[dest++] = a[cursor2++];
            //结尾处理退化的序列
            if (--len2 == 0)
                break outer;

            count2 = gallopLeft(tmp[cursor1], a, cursor2, len2, 0, c);
            if (count2 != 0) {
                System.arraycopy(a, cursor2, a, dest, count2);
                dest += count2;
                cursor2 += count2;
                len2 -= count2;
                if (len2 == 0)
                    break outer;
            }
            a[dest++] = tmp[cursor1++];
            if (--len1 == 1)
                break outer;
           
            // 这里对连续性比另外一个大的阈值减少,这样更容易触发这段操作,
            // 应该是因为前面的数据表现好,后面的数据类似的可能性更
            minGallop--;
      
          //如果连续性还是很大的话,继续这样处理 s
        } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
      
        if (minGallop < 0)
            minGallop = 0;
        
        // 同样,这里如果跳出了那段循环,就证明数据的顺序程度不好,应当增加阈值,避免浪费资源
        minGallop += 2;  // Penalize for leaving gallop mode
    }  // End of "outer" loop
    this.minGallop = minGallop < 1 ? 1 : minGallop;  // Write back to field

    if (len1 == 1) {
        assert len2 > 0;
        System.arraycopy(a, cursor2, a, dest, len2);
        a[dest + len2] = tmp[cursor1]; //  Last elt of run 1 to end of merge
    } else if (len1 == 0) {
        throw new IllegalArgumentException(
            "Comparison method violates its general contract!");
    } else {
        assert len2 == 0;
        assert len1 > 1;
        System.arraycopy(tmp, cursor1, a, dest, len1);
    }
}

/**
 * Like mergeLo, except that this method should be called only if
 * len1 >= len2; mergeLo should be called if len1 <= len2.  (Either method
 * may be called if len1 == len2.)
 *
 * @param base1 index of first element in first run to be merged
 * @param len1  length of first run to be merged (must be > 0)
 * @param base2 index of first element in second run to be merged
 *        (must be aBase + aLen)
 * @param len2  length of second run to be merged (must be > 0)
 */
private void mergeHi(int base1, int len1, int base2, int len2) {
    assert len1 > 0 && len2 > 0 && base1 + len1 == base2;

    // Copy second run into temp array
    T[] a = this.a; // For performance
    T[] tmp = ensureCapacity(len2);
    int tmpBase = this.tmpBase;
    System.arraycopy(a, base2, tmp, tmpBase, len2);

    int cursor1 = base1 + len1 - 1;  // Indexes into a
    int cursor2 = tmpBase + len2 - 1; // Indexes into tmp array
    int dest = base2 + len2 - 1;     // Indexes into a

    // Move last element of first run and deal with degenerate cases
    a[dest--] = a[cursor1--];
    if (--len1 == 0) {
        System.arraycopy(tmp, tmpBase, a, dest - (len2 - 1), len2);
        return;
    }
    if (len2 == 1) {
        dest -= len1;
        cursor1 -= len1;
        System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
        a[dest] = tmp[cursor2];
        return;
    }

    Comparator<? super T> c = this.c;  // Use local variable for performance
    int minGallop = this.minGallop;    //  "    "       "     "      "
outer:
    while (true) {
        int count1 = 0; // Number of times in a row that first run won
        int count2 = 0; // Number of times in a row that second run won

        /*
         * Do the straightforward thing until (if ever) one run
         * appears to win consistently.
         */
        do {
            assert len1 > 0 && len2 > 1;
            if (c.compare(tmp[cursor2], a[cursor1]) < 0) {
                a[dest--] = a[cursor1--];
                count1++;
                count2 = 0;
                if (--len1 == 0)
                    break outer;
            } else {
                a[dest--] = tmp[cursor2--];
                count2++;
                count1 = 0;
                if (--len2 == 1)
                    break outer;
            }
        } while ((count1 | count2) < minGallop);

        /*
         * One run is winning so consistently that galloping may be a
         * huge win. So try that, and continue galloping until (if ever)
         * neither run appears to be winning consistently anymore.
         */
        do {
            assert len1 > 0 && len2 > 1;
            count1 = len1 - gallopRight(tmp[cursor2], a, base1, len1, len1 - 1, c);
            if (count1 != 0) {
                dest -= count1;
                cursor1 -= count1;
                len1 -= count1;
                System.arraycopy(a, cursor1 + 1, a, dest + 1, count1);
                if (len1 == 0)
                    break outer;
            }
            a[dest--] = tmp[cursor2--];
            if (--len2 == 1)
                break outer;

            count2 = len2 - gallopLeft(a[cursor1], tmp, tmpBase, len2, len2 - 1, c);
            if (count2 != 0) {
                dest -= count2;
                cursor2 -= count2;
                len2 -= count2;
                System.arraycopy(tmp, cursor2 + 1, a, dest + 1, count2);
                if (len2 <= 1)  // len2 == 1 || len2 == 0
                    break outer;
            }
            a[dest--] = a[cursor1--];
            if (--len1 == 0)
                break outer;
            minGallop--;
        } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
        if (minGallop < 0)
            minGallop = 0;
        minGallop += 2;  // Penalize for leaving gallop mode
    }  // End of "outer" loop
    this.minGallop = minGallop < 1 ? 1 : minGallop;  // Write back to field

    if (len2 == 1) {
        assert len1 > 0;
        dest -= len1;
        cursor1 -= len1;
        System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
        a[dest] = tmp[cursor2];  // Move first elt of run2 to front of merge
    } else if (len2 == 0) {
        throw new IllegalArgumentException(
            "Comparison method violates its general contract!");
    } else {
        assert len1 == 0;
        assert len2 > 0;
        System.arraycopy(tmp, tmpBase, a, dest - (len2 - 1), len2);
    }
}

/**
 * Merges all runs on the stack until only one remains.  This method is
 * called once, to complete the sort.
 * 合并栈中所有待合并的序列,最后剩下一个序列。这个方法在整次排序中只执行一次
 */
private void mergeForceCollapse() {
    while (stackSize > 1) {
        int n = stackSize - 2;
        if (n > 0 && runLen[n - 1] < runLen[n + 1])
            n--;
        mergeAt(n);
    }
}

说明

breakcontinue :都是结束循环的作用,但是它只能结束它外面的第一层循环。如果代码里面是一层一层又一层的循环,想直接结束最外层循环此时,就需要 outer 了。

outer:就相当于表示它现在代表的某个循环。如果想跳出它所代表的循环,那么就 break outer;如果想结束它所代表的此次循环,那么就 continue outer;

// 用 break outer 则输出:0
// 用 break 输出:000000000

outer:
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            if(j==0) {
                System.out.print(j);
            }else {
                break outer; 
                // break;
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值