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