rt/emul/compact/src/main/java/java/util/ComparableTimSort.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 26 Feb 2013 16:54:16 +0100
changeset 772 d382dacfd73f
parent 636 emul/compact/src/main/java/java/util/ComparableTimSort.java@8d0be6a9a809
permissions -rw-r--r--
Moving modules around so the runtime is under one master pom and can be built without building other modules that are in the repository
jaroslav@559
     1
/*
jaroslav@559
     2
 * Copyright 2009 Google Inc.  All Rights Reserved.
jaroslav@559
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@559
     4
 *
jaroslav@559
     5
 * This code is free software; you can redistribute it and/or modify it
jaroslav@559
     6
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@559
     7
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@559
     8
 * particular file as subject to the "Classpath" exception as provided
jaroslav@559
     9
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@559
    10
 *
jaroslav@559
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@559
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@559
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@559
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@559
    15
 * accompanied this code).
jaroslav@559
    16
 *
jaroslav@559
    17
 * You should have received a copy of the GNU General Public License version
jaroslav@559
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@559
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@559
    20
 *
jaroslav@559
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@559
    22
 * or visit www.oracle.com if you need additional information or have any
jaroslav@559
    23
 * questions.
jaroslav@559
    24
 */
jaroslav@559
    25
jaroslav@559
    26
package java.util;
jaroslav@559
    27
jaroslav@568
    28
jaroslav@559
    29
/**
jaroslav@559
    30
 * This is a near duplicate of {@link TimSort}, modified for use with
jaroslav@559
    31
 * arrays of objects that implement {@link Comparable}, instead of using
jaroslav@559
    32
 * explicit comparators.
jaroslav@559
    33
 *
jaroslav@559
    34
 * <p>If you are using an optimizing VM, you may find that ComparableTimSort
jaroslav@559
    35
 * offers no performance benefit over TimSort in conjunction with a
jaroslav@559
    36
 * comparator that simply returns {@code ((Comparable)first).compareTo(Second)}.
jaroslav@559
    37
 * If this is the case, you are better off deleting ComparableTimSort to
jaroslav@559
    38
 * eliminate the code duplication.  (See Arrays.java for details.)
jaroslav@559
    39
 *
jaroslav@559
    40
 * @author Josh Bloch
jaroslav@559
    41
 */
jaroslav@559
    42
class ComparableTimSort {
jaroslav@559
    43
    /**
jaroslav@559
    44
     * This is the minimum sized sequence that will be merged.  Shorter
jaroslav@559
    45
     * sequences will be lengthened by calling binarySort.  If the entire
jaroslav@559
    46
     * array is less than this length, no merges will be performed.
jaroslav@559
    47
     *
jaroslav@559
    48
     * This constant should be a power of two.  It was 64 in Tim Peter's C
jaroslav@559
    49
     * implementation, but 32 was empirically determined to work better in
jaroslav@559
    50
     * this implementation.  In the unlikely event that you set this constant
jaroslav@559
    51
     * to be a number that's not a power of two, you'll need to change the
jaroslav@559
    52
     * {@link #minRunLength} computation.
jaroslav@559
    53
     *
jaroslav@559
    54
     * If you decrease this constant, you must change the stackLen
jaroslav@559
    55
     * computation in the TimSort constructor, or you risk an
jaroslav@559
    56
     * ArrayOutOfBounds exception.  See listsort.txt for a discussion
jaroslav@559
    57
     * of the minimum stack length required as a function of the length
jaroslav@559
    58
     * of the array being sorted and the minimum merge sequence length.
jaroslav@559
    59
     */
jaroslav@559
    60
    private static final int MIN_MERGE = 32;
jaroslav@559
    61
jaroslav@559
    62
    /**
jaroslav@559
    63
     * The array being sorted.
jaroslav@559
    64
     */
jaroslav@559
    65
    private final Object[] a;
jaroslav@559
    66
jaroslav@559
    67
    /**
jaroslav@559
    68
     * When we get into galloping mode, we stay there until both runs win less
jaroslav@559
    69
     * often than MIN_GALLOP consecutive times.
jaroslav@559
    70
     */
jaroslav@559
    71
    private static final int  MIN_GALLOP = 7;
jaroslav@559
    72
jaroslav@559
    73
    /**
jaroslav@559
    74
     * This controls when we get *into* galloping mode.  It is initialized
jaroslav@559
    75
     * to MIN_GALLOP.  The mergeLo and mergeHi methods nudge it higher for
jaroslav@559
    76
     * random data, and lower for highly structured data.
jaroslav@559
    77
     */
jaroslav@559
    78
    private int minGallop = MIN_GALLOP;
jaroslav@559
    79
jaroslav@559
    80
    /**
jaroslav@559
    81
     * Maximum initial size of tmp array, which is used for merging.  The array
jaroslav@559
    82
     * can grow to accommodate demand.
jaroslav@559
    83
     *
jaroslav@559
    84
     * Unlike Tim's original C version, we do not allocate this much storage
jaroslav@559
    85
     * when sorting smaller arrays.  This change was required for performance.
jaroslav@559
    86
     */
jaroslav@559
    87
    private static final int INITIAL_TMP_STORAGE_LENGTH = 256;
jaroslav@559
    88
jaroslav@559
    89
    /**
jaroslav@559
    90
     * Temp storage for merges.
jaroslav@559
    91
     */
jaroslav@559
    92
    private Object[] tmp;
jaroslav@559
    93
jaroslav@559
    94
    /**
jaroslav@559
    95
     * A stack of pending runs yet to be merged.  Run i starts at
jaroslav@559
    96
     * address base[i] and extends for len[i] elements.  It's always
jaroslav@559
    97
     * true (so long as the indices are in bounds) that:
jaroslav@559
    98
     *
jaroslav@559
    99
     *     runBase[i] + runLen[i] == runBase[i + 1]
jaroslav@559
   100
     *
jaroslav@559
   101
     * so we could cut the storage for this, but it's a minor amount,
jaroslav@559
   102
     * and keeping all the info explicit simplifies the code.
jaroslav@559
   103
     */
jaroslav@559
   104
    private int stackSize = 0;  // Number of pending runs on stack
jaroslav@559
   105
    private final int[] runBase;
jaroslav@559
   106
    private final int[] runLen;
jaroslav@559
   107
jaroslav@559
   108
    /**
jaroslav@559
   109
     * Creates a TimSort instance to maintain the state of an ongoing sort.
jaroslav@559
   110
     *
jaroslav@559
   111
     * @param a the array to be sorted
jaroslav@559
   112
     */
jaroslav@559
   113
    private ComparableTimSort(Object[] a) {
jaroslav@559
   114
        this.a = a;
jaroslav@559
   115
jaroslav@559
   116
        // Allocate temp storage (which may be increased later if necessary)
jaroslav@559
   117
        int len = a.length;
jaroslav@559
   118
        @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
jaroslav@559
   119
        Object[] newArray = new Object[len < 2 * INITIAL_TMP_STORAGE_LENGTH ?
jaroslav@559
   120
                                       len >>> 1 : INITIAL_TMP_STORAGE_LENGTH];
jaroslav@559
   121
        tmp = newArray;
jaroslav@559
   122
jaroslav@559
   123
        /*
jaroslav@559
   124
         * Allocate runs-to-be-merged stack (which cannot be expanded).  The
jaroslav@559
   125
         * stack length requirements are described in listsort.txt.  The C
jaroslav@559
   126
         * version always uses the same stack length (85), but this was
jaroslav@559
   127
         * measured to be too expensive when sorting "mid-sized" arrays (e.g.,
jaroslav@559
   128
         * 100 elements) in Java.  Therefore, we use smaller (but sufficiently
jaroslav@559
   129
         * large) stack lengths for smaller arrays.  The "magic numbers" in the
jaroslav@559
   130
         * computation below must be changed if MIN_MERGE is decreased.  See
jaroslav@559
   131
         * the MIN_MERGE declaration above for more information.
jaroslav@559
   132
         */
jaroslav@559
   133
        int stackLen = (len <    120  ?  5 :
jaroslav@559
   134
                        len <   1542  ? 10 :
jaroslav@559
   135
                        len < 119151  ? 19 : 40);
jaroslav@559
   136
        runBase = new int[stackLen];
jaroslav@559
   137
        runLen = new int[stackLen];
jaroslav@559
   138
    }
jaroslav@559
   139
jaroslav@559
   140
    /*
jaroslav@559
   141
     * The next two methods (which are package private and static) constitute
jaroslav@559
   142
     * the entire API of this class.  Each of these methods obeys the contract
jaroslav@559
   143
     * of the public method with the same signature in java.util.Arrays.
jaroslav@559
   144
     */
jaroslav@559
   145
jaroslav@559
   146
    static void sort(Object[] a) {
jaroslav@559
   147
          sort(a, 0, a.length);
jaroslav@559
   148
    }
jaroslav@559
   149
jaroslav@559
   150
    static void sort(Object[] a, int lo, int hi) {
jaroslav@559
   151
        rangeCheck(a.length, lo, hi);
jaroslav@559
   152
        int nRemaining  = hi - lo;
jaroslav@559
   153
        if (nRemaining < 2)
jaroslav@559
   154
            return;  // Arrays of size 0 and 1 are always sorted
jaroslav@559
   155
jaroslav@559
   156
        // If array is small, do a "mini-TimSort" with no merges
jaroslav@559
   157
        if (nRemaining < MIN_MERGE) {
jaroslav@559
   158
            int initRunLen = countRunAndMakeAscending(a, lo, hi);
jaroslav@559
   159
            binarySort(a, lo, hi, lo + initRunLen);
jaroslav@559
   160
            return;
jaroslav@559
   161
        }
jaroslav@559
   162
jaroslav@559
   163
        /**
jaroslav@559
   164
         * March over the array once, left to right, finding natural runs,
jaroslav@559
   165
         * extending short natural runs to minRun elements, and merging runs
jaroslav@559
   166
         * to maintain stack invariant.
jaroslav@559
   167
         */
jaroslav@559
   168
        ComparableTimSort ts = new ComparableTimSort(a);
jaroslav@559
   169
        int minRun = minRunLength(nRemaining);
jaroslav@559
   170
        do {
jaroslav@559
   171
            // Identify next run
jaroslav@559
   172
            int runLen = countRunAndMakeAscending(a, lo, hi);
jaroslav@559
   173
jaroslav@559
   174
            // If run is short, extend to min(minRun, nRemaining)
jaroslav@559
   175
            if (runLen < minRun) {
jaroslav@559
   176
                int force = nRemaining <= minRun ? nRemaining : minRun;
jaroslav@559
   177
                binarySort(a, lo, lo + force, lo + runLen);
jaroslav@559
   178
                runLen = force;
jaroslav@559
   179
            }
jaroslav@559
   180
jaroslav@559
   181
            // Push run onto pending-run stack, and maybe merge
jaroslav@559
   182
            ts.pushRun(lo, runLen);
jaroslav@559
   183
            ts.mergeCollapse();
jaroslav@559
   184
jaroslav@559
   185
            // Advance to find next run
jaroslav@559
   186
            lo += runLen;
jaroslav@559
   187
            nRemaining -= runLen;
jaroslav@559
   188
        } while (nRemaining != 0);
jaroslav@559
   189
jaroslav@559
   190
        // Merge all remaining runs to complete sort
jaroslav@559
   191
        assert lo == hi;
jaroslav@559
   192
        ts.mergeForceCollapse();
jaroslav@559
   193
        assert ts.stackSize == 1;
jaroslav@559
   194
    }
jaroslav@559
   195
jaroslav@559
   196
    /**
jaroslav@559
   197
     * Sorts the specified portion of the specified array using a binary
jaroslav@559
   198
     * insertion sort.  This is the best method for sorting small numbers
jaroslav@559
   199
     * of elements.  It requires O(n log n) compares, but O(n^2) data
jaroslav@559
   200
     * movement (worst case).
jaroslav@559
   201
     *
jaroslav@559
   202
     * If the initial part of the specified range is already sorted,
jaroslav@559
   203
     * this method can take advantage of it: the method assumes that the
jaroslav@559
   204
     * elements from index {@code lo}, inclusive, to {@code start},
jaroslav@559
   205
     * exclusive are already sorted.
jaroslav@559
   206
     *
jaroslav@559
   207
     * @param a the array in which a range is to be sorted
jaroslav@559
   208
     * @param lo the index of the first element in the range to be sorted
jaroslav@559
   209
     * @param hi the index after the last element in the range to be sorted
jaroslav@559
   210
     * @param start the index of the first element in the range that is
jaroslav@559
   211
     *        not already known to be sorted ({@code lo <= start <= hi})
jaroslav@559
   212
     */
jaroslav@559
   213
    @SuppressWarnings("fallthrough")
jaroslav@559
   214
    private static void binarySort(Object[] a, int lo, int hi, int start) {
jaroslav@559
   215
        assert lo <= start && start <= hi;
jaroslav@559
   216
        if (start == lo)
jaroslav@559
   217
            start++;
jaroslav@559
   218
        for ( ; start < hi; start++) {
jaroslav@559
   219
            @SuppressWarnings("unchecked")
jaroslav@559
   220
            Comparable<Object> pivot = (Comparable) a[start];
jaroslav@559
   221
jaroslav@559
   222
            // Set left (and right) to the index where a[start] (pivot) belongs
jaroslav@559
   223
            int left = lo;
jaroslav@559
   224
            int right = start;
jaroslav@559
   225
            assert left <= right;
jaroslav@559
   226
            /*
jaroslav@559
   227
             * Invariants:
jaroslav@559
   228
             *   pivot >= all in [lo, left).
jaroslav@559
   229
             *   pivot <  all in [right, start).
jaroslav@559
   230
             */
jaroslav@559
   231
            while (left < right) {
jaroslav@559
   232
                int mid = (left + right) >>> 1;
jaroslav@559
   233
                if (pivot.compareTo(a[mid]) < 0)
jaroslav@559
   234
                    right = mid;
jaroslav@559
   235
                else
jaroslav@559
   236
                    left = mid + 1;
jaroslav@559
   237
            }
jaroslav@559
   238
            assert left == right;
jaroslav@559
   239
jaroslav@559
   240
            /*
jaroslav@559
   241
             * The invariants still hold: pivot >= all in [lo, left) and
jaroslav@559
   242
             * pivot < all in [left, start), so pivot belongs at left.  Note
jaroslav@559
   243
             * that if there are elements equal to pivot, left points to the
jaroslav@559
   244
             * first slot after them -- that's why this sort is stable.
jaroslav@559
   245
             * Slide elements over to make room for pivot.
jaroslav@559
   246
             */
jaroslav@559
   247
            int n = start - left;  // The number of elements to move
jaroslav@559
   248
            // Switch is just an optimization for arraycopy in default case
jaroslav@559
   249
            switch (n) {
jaroslav@559
   250
                case 2:  a[left + 2] = a[left + 1];
jaroslav@559
   251
                case 1:  a[left + 1] = a[left];
jaroslav@559
   252
                         break;
jaroslav@559
   253
                default: System.arraycopy(a, left, a, left + 1, n);
jaroslav@559
   254
            }
jaroslav@559
   255
            a[left] = pivot;
jaroslav@559
   256
        }
jaroslav@559
   257
    }
jaroslav@559
   258
jaroslav@559
   259
    /**
jaroslav@559
   260
     * Returns the length of the run beginning at the specified position in
jaroslav@559
   261
     * the specified array and reverses the run if it is descending (ensuring
jaroslav@559
   262
     * that the run will always be ascending when the method returns).
jaroslav@559
   263
     *
jaroslav@559
   264
     * A run is the longest ascending sequence with:
jaroslav@559
   265
     *
jaroslav@559
   266
     *    a[lo] <= a[lo + 1] <= a[lo + 2] <= ...
jaroslav@559
   267
     *
jaroslav@559
   268
     * or the longest descending sequence with:
jaroslav@559
   269
     *
jaroslav@559
   270
     *    a[lo] >  a[lo + 1] >  a[lo + 2] >  ...
jaroslav@559
   271
     *
jaroslav@559
   272
     * For its intended use in a stable mergesort, the strictness of the
jaroslav@559
   273
     * definition of "descending" is needed so that the call can safely
jaroslav@559
   274
     * reverse a descending sequence without violating stability.
jaroslav@559
   275
     *
jaroslav@559
   276
     * @param a the array in which a run is to be counted and possibly reversed
jaroslav@559
   277
     * @param lo index of the first element in the run
jaroslav@559
   278
     * @param hi index after the last element that may be contained in the run.
jaroslav@559
   279
              It is required that {@code lo < hi}.
jaroslav@559
   280
     * @return  the length of the run beginning at the specified position in
jaroslav@559
   281
     *          the specified array
jaroslav@559
   282
     */
jaroslav@559
   283
    @SuppressWarnings("unchecked")
jaroslav@559
   284
    private static int countRunAndMakeAscending(Object[] a, int lo, int hi) {
jaroslav@559
   285
        assert lo < hi;
jaroslav@559
   286
        int runHi = lo + 1;
jaroslav@559
   287
        if (runHi == hi)
jaroslav@559
   288
            return 1;
jaroslav@559
   289
jaroslav@559
   290
        // Find end of run, and reverse range if descending
jaroslav@559
   291
        if (((Comparable) a[runHi++]).compareTo(a[lo]) < 0) { // Descending
jaroslav@559
   292
            while (runHi < hi && ((Comparable) a[runHi]).compareTo(a[runHi - 1]) < 0)
jaroslav@559
   293
                runHi++;
jaroslav@559
   294
            reverseRange(a, lo, runHi);
jaroslav@559
   295
        } else {                              // Ascending
jaroslav@559
   296
            while (runHi < hi && ((Comparable) a[runHi]).compareTo(a[runHi - 1]) >= 0)
jaroslav@559
   297
                runHi++;
jaroslav@559
   298
        }
jaroslav@559
   299
jaroslav@559
   300
        return runHi - lo;
jaroslav@559
   301
    }
jaroslav@559
   302
jaroslav@559
   303
    /**
jaroslav@559
   304
     * Reverse the specified range of the specified array.
jaroslav@559
   305
     *
jaroslav@559
   306
     * @param a the array in which a range is to be reversed
jaroslav@559
   307
     * @param lo the index of the first element in the range to be reversed
jaroslav@559
   308
     * @param hi the index after the last element in the range to be reversed
jaroslav@559
   309
     */
jaroslav@559
   310
    private static void reverseRange(Object[] a, int lo, int hi) {
jaroslav@559
   311
        hi--;
jaroslav@559
   312
        while (lo < hi) {
jaroslav@559
   313
            Object t = a[lo];
jaroslav@559
   314
            a[lo++] = a[hi];
jaroslav@559
   315
            a[hi--] = t;
jaroslav@559
   316
        }
jaroslav@559
   317
    }
jaroslav@559
   318
jaroslav@559
   319
    /**
jaroslav@559
   320
     * Returns the minimum acceptable run length for an array of the specified
jaroslav@559
   321
     * length. Natural runs shorter than this will be extended with
jaroslav@559
   322
     * {@link #binarySort}.
jaroslav@559
   323
     *
jaroslav@559
   324
     * Roughly speaking, the computation is:
jaroslav@559
   325
     *
jaroslav@559
   326
     *  If n < MIN_MERGE, return n (it's too small to bother with fancy stuff).
jaroslav@559
   327
     *  Else if n is an exact power of 2, return MIN_MERGE/2.
jaroslav@559
   328
     *  Else return an int k, MIN_MERGE/2 <= k <= MIN_MERGE, such that n/k
jaroslav@559
   329
     *   is close to, but strictly less than, an exact power of 2.
jaroslav@559
   330
     *
jaroslav@559
   331
     * For the rationale, see listsort.txt.
jaroslav@559
   332
     *
jaroslav@559
   333
     * @param n the length of the array to be sorted
jaroslav@559
   334
     * @return the length of the minimum run to be merged
jaroslav@559
   335
     */
jaroslav@559
   336
    private static int minRunLength(int n) {
jaroslav@559
   337
        assert n >= 0;
jaroslav@559
   338
        int r = 0;      // Becomes 1 if any 1 bits are shifted off
jaroslav@559
   339
        while (n >= MIN_MERGE) {
jaroslav@559
   340
            r |= (n & 1);
jaroslav@559
   341
            n >>= 1;
jaroslav@559
   342
        }
jaroslav@559
   343
        return n + r;
jaroslav@559
   344
    }
jaroslav@559
   345
jaroslav@559
   346
    /**
jaroslav@559
   347
     * Pushes the specified run onto the pending-run stack.
jaroslav@559
   348
     *
jaroslav@559
   349
     * @param runBase index of the first element in the run
jaroslav@559
   350
     * @param runLen  the number of elements in the run
jaroslav@559
   351
     */
jaroslav@559
   352
    private void pushRun(int runBase, int runLen) {
jaroslav@559
   353
        this.runBase[stackSize] = runBase;
jaroslav@559
   354
        this.runLen[stackSize] = runLen;
jaroslav@559
   355
        stackSize++;
jaroslav@559
   356
    }
jaroslav@559
   357
jaroslav@559
   358
    /**
jaroslav@559
   359
     * Examines the stack of runs waiting to be merged and merges adjacent runs
jaroslav@559
   360
     * until the stack invariants are reestablished:
jaroslav@559
   361
     *
jaroslav@559
   362
     *     1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1]
jaroslav@559
   363
     *     2. runLen[i - 2] > runLen[i - 1]
jaroslav@559
   364
     *
jaroslav@559
   365
     * This method is called each time a new run is pushed onto the stack,
jaroslav@559
   366
     * so the invariants are guaranteed to hold for i < stackSize upon
jaroslav@559
   367
     * entry to the method.
jaroslav@559
   368
     */
jaroslav@559
   369
    private void mergeCollapse() {
jaroslav@559
   370
        while (stackSize > 1) {
jaroslav@559
   371
            int n = stackSize - 2;
jaroslav@559
   372
            if (n > 0 && runLen[n-1] <= runLen[n] + runLen[n+1]) {
jaroslav@559
   373
                if (runLen[n - 1] < runLen[n + 1])
jaroslav@559
   374
                    n--;
jaroslav@559
   375
                mergeAt(n);
jaroslav@559
   376
            } else if (runLen[n] <= runLen[n + 1]) {
jaroslav@559
   377
                mergeAt(n);
jaroslav@559
   378
            } else {
jaroslav@559
   379
                break; // Invariant is established
jaroslav@559
   380
            }
jaroslav@559
   381
        }
jaroslav@559
   382
    }
jaroslav@559
   383
jaroslav@559
   384
    /**
jaroslav@559
   385
     * Merges all runs on the stack until only one remains.  This method is
jaroslav@559
   386
     * called once, to complete the sort.
jaroslav@559
   387
     */
jaroslav@559
   388
    private void mergeForceCollapse() {
jaroslav@559
   389
        while (stackSize > 1) {
jaroslav@559
   390
            int n = stackSize - 2;
jaroslav@559
   391
            if (n > 0 && runLen[n - 1] < runLen[n + 1])
jaroslav@559
   392
                n--;
jaroslav@559
   393
            mergeAt(n);
jaroslav@559
   394
        }
jaroslav@559
   395
    }
jaroslav@559
   396
jaroslav@559
   397
    /**
jaroslav@559
   398
     * Merges the two runs at stack indices i and i+1.  Run i must be
jaroslav@559
   399
     * the penultimate or antepenultimate run on the stack.  In other words,
jaroslav@559
   400
     * i must be equal to stackSize-2 or stackSize-3.
jaroslav@559
   401
     *
jaroslav@559
   402
     * @param i stack index of the first of the two runs to merge
jaroslav@559
   403
     */
jaroslav@559
   404
    @SuppressWarnings("unchecked")
jaroslav@559
   405
    private void mergeAt(int i) {
jaroslav@559
   406
        assert stackSize >= 2;
jaroslav@559
   407
        assert i >= 0;
jaroslav@559
   408
        assert i == stackSize - 2 || i == stackSize - 3;
jaroslav@559
   409
jaroslav@559
   410
        int base1 = runBase[i];
jaroslav@559
   411
        int len1 = runLen[i];
jaroslav@559
   412
        int base2 = runBase[i + 1];
jaroslav@559
   413
        int len2 = runLen[i + 1];
jaroslav@559
   414
        assert len1 > 0 && len2 > 0;
jaroslav@559
   415
        assert base1 + len1 == base2;
jaroslav@559
   416
jaroslav@559
   417
        /*
jaroslav@559
   418
         * Record the length of the combined runs; if i is the 3rd-last
jaroslav@559
   419
         * run now, also slide over the last run (which isn't involved
jaroslav@559
   420
         * in this merge).  The current run (i+1) goes away in any case.
jaroslav@559
   421
         */
jaroslav@559
   422
        runLen[i] = len1 + len2;
jaroslav@559
   423
        if (i == stackSize - 3) {
jaroslav@559
   424
            runBase[i + 1] = runBase[i + 2];
jaroslav@559
   425
            runLen[i + 1] = runLen[i + 2];
jaroslav@559
   426
        }
jaroslav@559
   427
        stackSize--;
jaroslav@559
   428
jaroslav@559
   429
        /*
jaroslav@559
   430
         * Find where the first element of run2 goes in run1. Prior elements
jaroslav@559
   431
         * in run1 can be ignored (because they're already in place).
jaroslav@559
   432
         */
jaroslav@559
   433
        int k = gallopRight((Comparable<Object>) a[base2], a, base1, len1, 0);
jaroslav@559
   434
        assert k >= 0;
jaroslav@559
   435
        base1 += k;
jaroslav@559
   436
        len1 -= k;
jaroslav@559
   437
        if (len1 == 0)
jaroslav@559
   438
            return;
jaroslav@559
   439
jaroslav@559
   440
        /*
jaroslav@559
   441
         * Find where the last element of run1 goes in run2. Subsequent elements
jaroslav@559
   442
         * in run2 can be ignored (because they're already in place).
jaroslav@559
   443
         */
jaroslav@559
   444
        len2 = gallopLeft((Comparable<Object>) a[base1 + len1 - 1], a,
jaroslav@559
   445
                base2, len2, len2 - 1);
jaroslav@559
   446
        assert len2 >= 0;
jaroslav@559
   447
        if (len2 == 0)
jaroslav@559
   448
            return;
jaroslav@559
   449
jaroslav@559
   450
        // Merge remaining runs, using tmp array with min(len1, len2) elements
jaroslav@559
   451
        if (len1 <= len2)
jaroslav@559
   452
            mergeLo(base1, len1, base2, len2);
jaroslav@559
   453
        else
jaroslav@559
   454
            mergeHi(base1, len1, base2, len2);
jaroslav@559
   455
    }
jaroslav@559
   456
jaroslav@559
   457
    /**
jaroslav@559
   458
     * Locates the position at which to insert the specified key into the
jaroslav@559
   459
     * specified sorted range; if the range contains an element equal to key,
jaroslav@559
   460
     * returns the index of the leftmost equal element.
jaroslav@559
   461
     *
jaroslav@559
   462
     * @param key the key whose insertion point to search for
jaroslav@559
   463
     * @param a the array in which to search
jaroslav@559
   464
     * @param base the index of the first element in the range
jaroslav@559
   465
     * @param len the length of the range; must be > 0
jaroslav@559
   466
     * @param hint the index at which to begin the search, 0 <= hint < n.
jaroslav@559
   467
     *     The closer hint is to the result, the faster this method will run.
jaroslav@559
   468
     * @return the int k,  0 <= k <= n such that a[b + k - 1] < key <= a[b + k],
jaroslav@559
   469
     *    pretending that a[b - 1] is minus infinity and a[b + n] is infinity.
jaroslav@559
   470
     *    In other words, key belongs at index b + k; or in other words,
jaroslav@559
   471
     *    the first k elements of a should precede key, and the last n - k
jaroslav@559
   472
     *    should follow it.
jaroslav@559
   473
     */
jaroslav@559
   474
    private static int gallopLeft(Comparable<Object> key, Object[] a,
jaroslav@559
   475
            int base, int len, int hint) {
jaroslav@559
   476
        assert len > 0 && hint >= 0 && hint < len;
jaroslav@559
   477
jaroslav@559
   478
        int lastOfs = 0;
jaroslav@559
   479
        int ofs = 1;
jaroslav@559
   480
        if (key.compareTo(a[base + hint]) > 0) {
jaroslav@559
   481
            // Gallop right until a[base+hint+lastOfs] < key <= a[base+hint+ofs]
jaroslav@559
   482
            int maxOfs = len - hint;
jaroslav@559
   483
            while (ofs < maxOfs && key.compareTo(a[base + hint + ofs]) > 0) {
jaroslav@559
   484
                lastOfs = ofs;
jaroslav@559
   485
                ofs = (ofs << 1) + 1;
jaroslav@559
   486
                if (ofs <= 0)   // int overflow
jaroslav@559
   487
                    ofs = maxOfs;
jaroslav@559
   488
            }
jaroslav@559
   489
            if (ofs > maxOfs)
jaroslav@559
   490
                ofs = maxOfs;
jaroslav@559
   491
jaroslav@559
   492
            // Make offsets relative to base
jaroslav@559
   493
            lastOfs += hint;
jaroslav@559
   494
            ofs += hint;
jaroslav@559
   495
        } else { // key <= a[base + hint]
jaroslav@559
   496
            // Gallop left until a[base+hint-ofs] < key <= a[base+hint-lastOfs]
jaroslav@559
   497
            final int maxOfs = hint + 1;
jaroslav@559
   498
            while (ofs < maxOfs && key.compareTo(a[base + hint - ofs]) <= 0) {
jaroslav@559
   499
                lastOfs = ofs;
jaroslav@559
   500
                ofs = (ofs << 1) + 1;
jaroslav@559
   501
                if (ofs <= 0)   // int overflow
jaroslav@559
   502
                    ofs = maxOfs;
jaroslav@559
   503
            }
jaroslav@559
   504
            if (ofs > maxOfs)
jaroslav@559
   505
                ofs = maxOfs;
jaroslav@559
   506
jaroslav@559
   507
            // Make offsets relative to base
jaroslav@559
   508
            int tmp = lastOfs;
jaroslav@559
   509
            lastOfs = hint - ofs;
jaroslav@559
   510
            ofs = hint - tmp;
jaroslav@559
   511
        }
jaroslav@559
   512
        assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
jaroslav@559
   513
jaroslav@559
   514
        /*
jaroslav@559
   515
         * Now a[base+lastOfs] < key <= a[base+ofs], so key belongs somewhere
jaroslav@559
   516
         * to the right of lastOfs but no farther right than ofs.  Do a binary
jaroslav@559
   517
         * search, with invariant a[base + lastOfs - 1] < key <= a[base + ofs].
jaroslav@559
   518
         */
jaroslav@559
   519
        lastOfs++;
jaroslav@559
   520
        while (lastOfs < ofs) {
jaroslav@559
   521
            int m = lastOfs + ((ofs - lastOfs) >>> 1);
jaroslav@559
   522
jaroslav@559
   523
            if (key.compareTo(a[base + m]) > 0)
jaroslav@559
   524
                lastOfs = m + 1;  // a[base + m] < key
jaroslav@559
   525
            else
jaroslav@559
   526
                ofs = m;          // key <= a[base + m]
jaroslav@559
   527
        }
jaroslav@559
   528
        assert lastOfs == ofs;    // so a[base + ofs - 1] < key <= a[base + ofs]
jaroslav@559
   529
        return ofs;
jaroslav@559
   530
    }
jaroslav@559
   531
jaroslav@559
   532
    /**
jaroslav@559
   533
     * Like gallopLeft, except that if the range contains an element equal to
jaroslav@559
   534
     * key, gallopRight returns the index after the rightmost equal element.
jaroslav@559
   535
     *
jaroslav@559
   536
     * @param key the key whose insertion point to search for
jaroslav@559
   537
     * @param a the array in which to search
jaroslav@559
   538
     * @param base the index of the first element in the range
jaroslav@559
   539
     * @param len the length of the range; must be > 0
jaroslav@559
   540
     * @param hint the index at which to begin the search, 0 <= hint < n.
jaroslav@559
   541
     *     The closer hint is to the result, the faster this method will run.
jaroslav@559
   542
     * @return the int k,  0 <= k <= n such that a[b + k - 1] <= key < a[b + k]
jaroslav@559
   543
     */
jaroslav@559
   544
    private static int gallopRight(Comparable<Object> key, Object[] a,
jaroslav@559
   545
            int base, int len, int hint) {
jaroslav@559
   546
        assert len > 0 && hint >= 0 && hint < len;
jaroslav@559
   547
jaroslav@559
   548
        int ofs = 1;
jaroslav@559
   549
        int lastOfs = 0;
jaroslav@559
   550
        if (key.compareTo(a[base + hint]) < 0) {
jaroslav@559
   551
            // Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs]
jaroslav@559
   552
            int maxOfs = hint + 1;
jaroslav@559
   553
            while (ofs < maxOfs && key.compareTo(a[base + hint - ofs]) < 0) {
jaroslav@559
   554
                lastOfs = ofs;
jaroslav@559
   555
                ofs = (ofs << 1) + 1;
jaroslav@559
   556
                if (ofs <= 0)   // int overflow
jaroslav@559
   557
                    ofs = maxOfs;
jaroslav@559
   558
            }
jaroslav@559
   559
            if (ofs > maxOfs)
jaroslav@559
   560
                ofs = maxOfs;
jaroslav@559
   561
jaroslav@559
   562
            // Make offsets relative to b
jaroslav@559
   563
            int tmp = lastOfs;
jaroslav@559
   564
            lastOfs = hint - ofs;
jaroslav@559
   565
            ofs = hint - tmp;
jaroslav@559
   566
        } else { // a[b + hint] <= key
jaroslav@559
   567
            // Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs]
jaroslav@559
   568
            int maxOfs = len - hint;
jaroslav@559
   569
            while (ofs < maxOfs && key.compareTo(a[base + hint + ofs]) >= 0) {
jaroslav@559
   570
                lastOfs = ofs;
jaroslav@559
   571
                ofs = (ofs << 1) + 1;
jaroslav@559
   572
                if (ofs <= 0)   // int overflow
jaroslav@559
   573
                    ofs = maxOfs;
jaroslav@559
   574
            }
jaroslav@559
   575
            if (ofs > maxOfs)
jaroslav@559
   576
                ofs = maxOfs;
jaroslav@559
   577
jaroslav@559
   578
            // Make offsets relative to b
jaroslav@559
   579
            lastOfs += hint;
jaroslav@559
   580
            ofs += hint;
jaroslav@559
   581
        }
jaroslav@559
   582
        assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
jaroslav@559
   583
jaroslav@559
   584
        /*
jaroslav@559
   585
         * Now a[b + lastOfs] <= key < a[b + ofs], so key belongs somewhere to
jaroslav@559
   586
         * the right of lastOfs but no farther right than ofs.  Do a binary
jaroslav@559
   587
         * search, with invariant a[b + lastOfs - 1] <= key < a[b + ofs].
jaroslav@559
   588
         */
jaroslav@559
   589
        lastOfs++;
jaroslav@559
   590
        while (lastOfs < ofs) {
jaroslav@559
   591
            int m = lastOfs + ((ofs - lastOfs) >>> 1);
jaroslav@559
   592
jaroslav@559
   593
            if (key.compareTo(a[base + m]) < 0)
jaroslav@559
   594
                ofs = m;          // key < a[b + m]
jaroslav@559
   595
            else
jaroslav@559
   596
                lastOfs = m + 1;  // a[b + m] <= key
jaroslav@559
   597
        }
jaroslav@559
   598
        assert lastOfs == ofs;    // so a[b + ofs - 1] <= key < a[b + ofs]
jaroslav@559
   599
        return ofs;
jaroslav@559
   600
    }
jaroslav@559
   601
jaroslav@559
   602
    /**
jaroslav@559
   603
     * Merges two adjacent runs in place, in a stable fashion.  The first
jaroslav@559
   604
     * element of the first run must be greater than the first element of the
jaroslav@559
   605
     * second run (a[base1] > a[base2]), and the last element of the first run
jaroslav@559
   606
     * (a[base1 + len1-1]) must be greater than all elements of the second run.
jaroslav@559
   607
     *
jaroslav@559
   608
     * For performance, this method should be called only when len1 <= len2;
jaroslav@559
   609
     * its twin, mergeHi should be called if len1 >= len2.  (Either method
jaroslav@559
   610
     * may be called if len1 == len2.)
jaroslav@559
   611
     *
jaroslav@559
   612
     * @param base1 index of first element in first run to be merged
jaroslav@559
   613
     * @param len1  length of first run to be merged (must be > 0)
jaroslav@559
   614
     * @param base2 index of first element in second run to be merged
jaroslav@559
   615
     *        (must be aBase + aLen)
jaroslav@559
   616
     * @param len2  length of second run to be merged (must be > 0)
jaroslav@559
   617
     */
jaroslav@559
   618
    @SuppressWarnings("unchecked")
jaroslav@559
   619
    private void mergeLo(int base1, int len1, int base2, int len2) {
jaroslav@559
   620
        assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
jaroslav@559
   621
jaroslav@559
   622
        // Copy first run into temp array
jaroslav@559
   623
        Object[] a = this.a; // For performance
jaroslav@559
   624
        Object[] tmp = ensureCapacity(len1);
jaroslav@559
   625
        System.arraycopy(a, base1, tmp, 0, len1);
jaroslav@559
   626
jaroslav@559
   627
        int cursor1 = 0;       // Indexes into tmp array
jaroslav@559
   628
        int cursor2 = base2;   // Indexes int a
jaroslav@559
   629
        int dest = base1;      // Indexes int a
jaroslav@559
   630
jaroslav@559
   631
        // Move first element of second run and deal with degenerate cases
jaroslav@559
   632
        a[dest++] = a[cursor2++];
jaroslav@559
   633
        if (--len2 == 0) {
jaroslav@559
   634
            System.arraycopy(tmp, cursor1, a, dest, len1);
jaroslav@559
   635
            return;
jaroslav@559
   636
        }
jaroslav@559
   637
        if (len1 == 1) {
jaroslav@559
   638
            System.arraycopy(a, cursor2, a, dest, len2);
jaroslav@559
   639
            a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge
jaroslav@559
   640
            return;
jaroslav@559
   641
        }
jaroslav@559
   642
jaroslav@559
   643
        int minGallop = this.minGallop;  // Use local variable for performance
jaroslav@559
   644
    outer:
jaroslav@559
   645
        while (true) {
jaroslav@559
   646
            int count1 = 0; // Number of times in a row that first run won
jaroslav@559
   647
            int count2 = 0; // Number of times in a row that second run won
jaroslav@559
   648
jaroslav@559
   649
            /*
jaroslav@559
   650
             * Do the straightforward thing until (if ever) one run starts
jaroslav@559
   651
             * winning consistently.
jaroslav@559
   652
             */
jaroslav@559
   653
            do {
jaroslav@559
   654
                assert len1 > 1 && len2 > 0;
jaroslav@559
   655
                if (((Comparable) a[cursor2]).compareTo(tmp[cursor1]) < 0) {
jaroslav@559
   656
                    a[dest++] = a[cursor2++];
jaroslav@559
   657
                    count2++;
jaroslav@559
   658
                    count1 = 0;
jaroslav@559
   659
                    if (--len2 == 0)
jaroslav@559
   660
                        break outer;
jaroslav@559
   661
                } else {
jaroslav@559
   662
                    a[dest++] = tmp[cursor1++];
jaroslav@559
   663
                    count1++;
jaroslav@559
   664
                    count2 = 0;
jaroslav@559
   665
                    if (--len1 == 1)
jaroslav@559
   666
                        break outer;
jaroslav@559
   667
                }
jaroslav@559
   668
            } while ((count1 | count2) < minGallop);
jaroslav@559
   669
jaroslav@559
   670
            /*
jaroslav@559
   671
             * One run is winning so consistently that galloping may be a
jaroslav@559
   672
             * huge win. So try that, and continue galloping until (if ever)
jaroslav@559
   673
             * neither run appears to be winning consistently anymore.
jaroslav@559
   674
             */
jaroslav@559
   675
            do {
jaroslav@559
   676
                assert len1 > 1 && len2 > 0;
jaroslav@559
   677
                count1 = gallopRight((Comparable) a[cursor2], tmp, cursor1, len1, 0);
jaroslav@559
   678
                if (count1 != 0) {
jaroslav@559
   679
                    System.arraycopy(tmp, cursor1, a, dest, count1);
jaroslav@559
   680
                    dest += count1;
jaroslav@559
   681
                    cursor1 += count1;
jaroslav@559
   682
                    len1 -= count1;
jaroslav@559
   683
                    if (len1 <= 1)  // len1 == 1 || len1 == 0
jaroslav@559
   684
                        break outer;
jaroslav@559
   685
                }
jaroslav@559
   686
                a[dest++] = a[cursor2++];
jaroslav@559
   687
                if (--len2 == 0)
jaroslav@559
   688
                    break outer;
jaroslav@559
   689
jaroslav@559
   690
                count2 = gallopLeft((Comparable) tmp[cursor1], a, cursor2, len2, 0);
jaroslav@559
   691
                if (count2 != 0) {
jaroslav@559
   692
                    System.arraycopy(a, cursor2, a, dest, count2);
jaroslav@559
   693
                    dest += count2;
jaroslav@559
   694
                    cursor2 += count2;
jaroslav@559
   695
                    len2 -= count2;
jaroslav@559
   696
                    if (len2 == 0)
jaroslav@559
   697
                        break outer;
jaroslav@559
   698
                }
jaroslav@559
   699
                a[dest++] = tmp[cursor1++];
jaroslav@559
   700
                if (--len1 == 1)
jaroslav@559
   701
                    break outer;
jaroslav@559
   702
                minGallop--;
jaroslav@559
   703
            } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
jaroslav@559
   704
            if (minGallop < 0)
jaroslav@559
   705
                minGallop = 0;
jaroslav@559
   706
            minGallop += 2;  // Penalize for leaving gallop mode
jaroslav@559
   707
        }  // End of "outer" loop
jaroslav@559
   708
        this.minGallop = minGallop < 1 ? 1 : minGallop;  // Write back to field
jaroslav@559
   709
jaroslav@559
   710
        if (len1 == 1) {
jaroslav@559
   711
            assert len2 > 0;
jaroslav@559
   712
            System.arraycopy(a, cursor2, a, dest, len2);
jaroslav@559
   713
            a[dest + len2] = tmp[cursor1]; //  Last elt of run 1 to end of merge
jaroslav@559
   714
        } else if (len1 == 0) {
jaroslav@559
   715
            throw new IllegalArgumentException(
jaroslav@559
   716
                "Comparison method violates its general contract!");
jaroslav@559
   717
        } else {
jaroslav@559
   718
            assert len2 == 0;
jaroslav@559
   719
            assert len1 > 1;
jaroslav@559
   720
            System.arraycopy(tmp, cursor1, a, dest, len1);
jaroslav@559
   721
        }
jaroslav@559
   722
    }
jaroslav@559
   723
jaroslav@559
   724
    /**
jaroslav@559
   725
     * Like mergeLo, except that this method should be called only if
jaroslav@559
   726
     * len1 >= len2; mergeLo should be called if len1 <= len2.  (Either method
jaroslav@559
   727
     * may be called if len1 == len2.)
jaroslav@559
   728
     *
jaroslav@559
   729
     * @param base1 index of first element in first run to be merged
jaroslav@559
   730
     * @param len1  length of first run to be merged (must be > 0)
jaroslav@559
   731
     * @param base2 index of first element in second run to be merged
jaroslav@559
   732
     *        (must be aBase + aLen)
jaroslav@559
   733
     * @param len2  length of second run to be merged (must be > 0)
jaroslav@559
   734
     */
jaroslav@559
   735
    @SuppressWarnings("unchecked")
jaroslav@559
   736
    private void mergeHi(int base1, int len1, int base2, int len2) {
jaroslav@559
   737
        assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
jaroslav@559
   738
jaroslav@559
   739
        // Copy second run into temp array
jaroslav@559
   740
        Object[] a = this.a; // For performance
jaroslav@559
   741
        Object[] tmp = ensureCapacity(len2);
jaroslav@559
   742
        System.arraycopy(a, base2, tmp, 0, len2);
jaroslav@559
   743
jaroslav@559
   744
        int cursor1 = base1 + len1 - 1;  // Indexes into a
jaroslav@559
   745
        int cursor2 = len2 - 1;          // Indexes into tmp array
jaroslav@559
   746
        int dest = base2 + len2 - 1;     // Indexes into a
jaroslav@559
   747
jaroslav@559
   748
        // Move last element of first run and deal with degenerate cases
jaroslav@559
   749
        a[dest--] = a[cursor1--];
jaroslav@559
   750
        if (--len1 == 0) {
jaroslav@559
   751
            System.arraycopy(tmp, 0, a, dest - (len2 - 1), len2);
jaroslav@559
   752
            return;
jaroslav@559
   753
        }
jaroslav@559
   754
        if (len2 == 1) {
jaroslav@559
   755
            dest -= len1;
jaroslav@559
   756
            cursor1 -= len1;
jaroslav@559
   757
            System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
jaroslav@559
   758
            a[dest] = tmp[cursor2];
jaroslav@559
   759
            return;
jaroslav@559
   760
        }
jaroslav@559
   761
jaroslav@559
   762
        int minGallop = this.minGallop;  // Use local variable for performance
jaroslav@559
   763
    outer:
jaroslav@559
   764
        while (true) {
jaroslav@559
   765
            int count1 = 0; // Number of times in a row that first run won
jaroslav@559
   766
            int count2 = 0; // Number of times in a row that second run won
jaroslav@559
   767
jaroslav@559
   768
            /*
jaroslav@559
   769
             * Do the straightforward thing until (if ever) one run
jaroslav@559
   770
             * appears to win consistently.
jaroslav@559
   771
             */
jaroslav@559
   772
            do {
jaroslav@559
   773
                assert len1 > 0 && len2 > 1;
jaroslav@559
   774
                if (((Comparable) tmp[cursor2]).compareTo(a[cursor1]) < 0) {
jaroslav@559
   775
                    a[dest--] = a[cursor1--];
jaroslav@559
   776
                    count1++;
jaroslav@559
   777
                    count2 = 0;
jaroslav@559
   778
                    if (--len1 == 0)
jaroslav@559
   779
                        break outer;
jaroslav@559
   780
                } else {
jaroslav@559
   781
                    a[dest--] = tmp[cursor2--];
jaroslav@559
   782
                    count2++;
jaroslav@559
   783
                    count1 = 0;
jaroslav@559
   784
                    if (--len2 == 1)
jaroslav@559
   785
                        break outer;
jaroslav@559
   786
                }
jaroslav@559
   787
            } while ((count1 | count2) < minGallop);
jaroslav@559
   788
jaroslav@559
   789
            /*
jaroslav@559
   790
             * One run is winning so consistently that galloping may be a
jaroslav@559
   791
             * huge win. So try that, and continue galloping until (if ever)
jaroslav@559
   792
             * neither run appears to be winning consistently anymore.
jaroslav@559
   793
             */
jaroslav@559
   794
            do {
jaroslav@559
   795
                assert len1 > 0 && len2 > 1;
jaroslav@559
   796
                count1 = len1 - gallopRight((Comparable) tmp[cursor2], a, base1, len1, len1 - 1);
jaroslav@559
   797
                if (count1 != 0) {
jaroslav@559
   798
                    dest -= count1;
jaroslav@559
   799
                    cursor1 -= count1;
jaroslav@559
   800
                    len1 -= count1;
jaroslav@559
   801
                    System.arraycopy(a, cursor1 + 1, a, dest + 1, count1);
jaroslav@559
   802
                    if (len1 == 0)
jaroslav@559
   803
                        break outer;
jaroslav@559
   804
                }
jaroslav@559
   805
                a[dest--] = tmp[cursor2--];
jaroslav@559
   806
                if (--len2 == 1)
jaroslav@559
   807
                    break outer;
jaroslav@559
   808
jaroslav@559
   809
                count2 = len2 - gallopLeft((Comparable) a[cursor1], tmp, 0, len2, len2 - 1);
jaroslav@559
   810
                if (count2 != 0) {
jaroslav@559
   811
                    dest -= count2;
jaroslav@559
   812
                    cursor2 -= count2;
jaroslav@559
   813
                    len2 -= count2;
jaroslav@559
   814
                    System.arraycopy(tmp, cursor2 + 1, a, dest + 1, count2);
jaroslav@559
   815
                    if (len2 <= 1)
jaroslav@559
   816
                        break outer; // len2 == 1 || len2 == 0
jaroslav@559
   817
                }
jaroslav@559
   818
                a[dest--] = a[cursor1--];
jaroslav@559
   819
                if (--len1 == 0)
jaroslav@559
   820
                    break outer;
jaroslav@559
   821
                minGallop--;
jaroslav@559
   822
            } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
jaroslav@559
   823
            if (minGallop < 0)
jaroslav@559
   824
                minGallop = 0;
jaroslav@559
   825
            minGallop += 2;  // Penalize for leaving gallop mode
jaroslav@559
   826
        }  // End of "outer" loop
jaroslav@559
   827
        this.minGallop = minGallop < 1 ? 1 : minGallop;  // Write back to field
jaroslav@559
   828
jaroslav@559
   829
        if (len2 == 1) {
jaroslav@559
   830
            assert len1 > 0;
jaroslav@559
   831
            dest -= len1;
jaroslav@559
   832
            cursor1 -= len1;
jaroslav@559
   833
            System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
jaroslav@559
   834
            a[dest] = tmp[cursor2];  // Move first elt of run2 to front of merge
jaroslav@559
   835
        } else if (len2 == 0) {
jaroslav@559
   836
            throw new IllegalArgumentException(
jaroslav@559
   837
                "Comparison method violates its general contract!");
jaroslav@559
   838
        } else {
jaroslav@559
   839
            assert len1 == 0;
jaroslav@559
   840
            assert len2 > 0;
jaroslav@559
   841
            System.arraycopy(tmp, 0, a, dest - (len2 - 1), len2);
jaroslav@559
   842
        }
jaroslav@559
   843
    }
jaroslav@559
   844
jaroslav@559
   845
    /**
jaroslav@559
   846
     * Ensures that the external array tmp has at least the specified
jaroslav@559
   847
     * number of elements, increasing its size if necessary.  The size
jaroslav@559
   848
     * increases exponentially to ensure amortized linear time complexity.
jaroslav@559
   849
     *
jaroslav@559
   850
     * @param minCapacity the minimum required capacity of the tmp array
jaroslav@559
   851
     * @return tmp, whether or not it grew
jaroslav@559
   852
     */
jaroslav@559
   853
    private Object[]  ensureCapacity(int minCapacity) {
jaroslav@559
   854
        if (tmp.length < minCapacity) {
jaroslav@559
   855
            // Compute smallest power of 2 > minCapacity
jaroslav@559
   856
            int newSize = minCapacity;
jaroslav@559
   857
            newSize |= newSize >> 1;
jaroslav@559
   858
            newSize |= newSize >> 2;
jaroslav@559
   859
            newSize |= newSize >> 4;
jaroslav@559
   860
            newSize |= newSize >> 8;
jaroslav@559
   861
            newSize |= newSize >> 16;
jaroslav@559
   862
            newSize++;
jaroslav@559
   863
jaroslav@559
   864
            if (newSize < 0) // Not bloody likely!
jaroslav@559
   865
                newSize = minCapacity;
jaroslav@559
   866
            else
jaroslav@559
   867
                newSize = Math.min(newSize, a.length >>> 1);
jaroslav@559
   868
jaroslav@559
   869
            @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
jaroslav@559
   870
            Object[] newArray = new Object[newSize];
jaroslav@559
   871
            tmp = newArray;
jaroslav@559
   872
        }
jaroslav@559
   873
        return tmp;
jaroslav@559
   874
    }
jaroslav@559
   875
jaroslav@559
   876
    /**
jaroslav@559
   877
     * Checks that fromIndex and toIndex are in range, and throws an
jaroslav@559
   878
     * appropriate exception if they aren't.
jaroslav@559
   879
     *
jaroslav@559
   880
     * @param arrayLen the length of the array
jaroslav@559
   881
     * @param fromIndex the index of the first element of the range
jaroslav@559
   882
     * @param toIndex the index after the last element of the range
jaroslav@559
   883
     * @throws IllegalArgumentException if fromIndex > toIndex
jaroslav@559
   884
     * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
jaroslav@559
   885
     *         or toIndex > arrayLen
jaroslav@559
   886
     */
jaroslav@559
   887
    private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
jaroslav@559
   888
        if (fromIndex > toIndex)
jaroslav@559
   889
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
jaroslav@559
   890
                       ") > toIndex(" + toIndex+")");
jaroslav@559
   891
        if (fromIndex < 0)
jaroslav@559
   892
            throw new ArrayIndexOutOfBoundsException(fromIndex);
jaroslav@559
   893
        if (toIndex > arrayLen)
jaroslav@559
   894
            throw new ArrayIndexOutOfBoundsException(toIndex);
jaroslav@559
   895
    }
jaroslav@559
   896
}