rt/emul/compact/src/main/java/java/util/TimSort.java
changeset 772 d382dacfd73f
parent 636 8d0be6a9a809
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/rt/emul/compact/src/main/java/java/util/TimSort.java	Tue Feb 26 16:54:16 2013 +0100
     1.3 @@ -0,0 +1,929 @@
     1.4 +/*
     1.5 + * Copyright 2009 Google Inc.  All Rights Reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.  Oracle designates this
    1.11 + * particular file as subject to the "Classpath" exception as provided
    1.12 + * by Oracle in the LICENSE file that accompanied this code.
    1.13 + *
    1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.17 + * version 2 for more details (a copy is included in the LICENSE file that
    1.18 + * accompanied this code).
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License version
    1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.23 + *
    1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.25 + * or visit www.oracle.com if you need additional information or have any
    1.26 + * questions.
    1.27 + */
    1.28 +
    1.29 +package java.util;
    1.30 +
    1.31 +
    1.32 +/**
    1.33 + * A stable, adaptive, iterative mergesort that requires far fewer than
    1.34 + * n lg(n) comparisons when running on partially sorted arrays, while
    1.35 + * offering performance comparable to a traditional mergesort when run
    1.36 + * on random arrays.  Like all proper mergesorts, this sort is stable and
    1.37 + * runs O(n log n) time (worst case).  In the worst case, this sort requires
    1.38 + * temporary storage space for n/2 object references; in the best case,
    1.39 + * it requires only a small constant amount of space.
    1.40 + *
    1.41 + * This implementation was adapted from Tim Peters's list sort for
    1.42 + * Python, which is described in detail here:
    1.43 + *
    1.44 + *   http://svn.python.org/projects/python/trunk/Objects/listsort.txt
    1.45 + *
    1.46 + * Tim's C code may be found here:
    1.47 + *
    1.48 + *   http://svn.python.org/projects/python/trunk/Objects/listobject.c
    1.49 + *
    1.50 + * The underlying techniques are described in this paper (and may have
    1.51 + * even earlier origins):
    1.52 + *
    1.53 + *  "Optimistic Sorting and Information Theoretic Complexity"
    1.54 + *  Peter McIlroy
    1.55 + *  SODA (Fourth Annual ACM-SIAM Symposium on Discrete Algorithms),
    1.56 + *  pp 467-474, Austin, Texas, 25-27 January 1993.
    1.57 + *
    1.58 + * While the API to this class consists solely of static methods, it is
    1.59 + * (privately) instantiable; a TimSort instance holds the state of an ongoing
    1.60 + * sort, assuming the input array is large enough to warrant the full-blown
    1.61 + * TimSort. Small arrays are sorted in place, using a binary insertion sort.
    1.62 + *
    1.63 + * @author Josh Bloch
    1.64 + */
    1.65 +class TimSort<T> {
    1.66 +    /**
    1.67 +     * This is the minimum sized sequence that will be merged.  Shorter
    1.68 +     * sequences will be lengthened by calling binarySort.  If the entire
    1.69 +     * array is less than this length, no merges will be performed.
    1.70 +     *
    1.71 +     * This constant should be a power of two.  It was 64 in Tim Peter's C
    1.72 +     * implementation, but 32 was empirically determined to work better in
    1.73 +     * this implementation.  In the unlikely event that you set this constant
    1.74 +     * to be a number that's not a power of two, you'll need to change the
    1.75 +     * {@link #minRunLength} computation.
    1.76 +     *
    1.77 +     * If you decrease this constant, you must change the stackLen
    1.78 +     * computation in the TimSort constructor, or you risk an
    1.79 +     * ArrayOutOfBounds exception.  See listsort.txt for a discussion
    1.80 +     * of the minimum stack length required as a function of the length
    1.81 +     * of the array being sorted and the minimum merge sequence length.
    1.82 +     */
    1.83 +    private static final int MIN_MERGE = 32;
    1.84 +
    1.85 +    /**
    1.86 +     * The array being sorted.
    1.87 +     */
    1.88 +    private final T[] a;
    1.89 +
    1.90 +    /**
    1.91 +     * The comparator for this sort.
    1.92 +     */
    1.93 +    private final Comparator<? super T> c;
    1.94 +
    1.95 +    /**
    1.96 +     * When we get into galloping mode, we stay there until both runs win less
    1.97 +     * often than MIN_GALLOP consecutive times.
    1.98 +     */
    1.99 +    private static final int  MIN_GALLOP = 7;
   1.100 +
   1.101 +    /**
   1.102 +     * This controls when we get *into* galloping mode.  It is initialized
   1.103 +     * to MIN_GALLOP.  The mergeLo and mergeHi methods nudge it higher for
   1.104 +     * random data, and lower for highly structured data.
   1.105 +     */
   1.106 +    private int minGallop = MIN_GALLOP;
   1.107 +
   1.108 +    /**
   1.109 +     * Maximum initial size of tmp array, which is used for merging.  The array
   1.110 +     * can grow to accommodate demand.
   1.111 +     *
   1.112 +     * Unlike Tim's original C version, we do not allocate this much storage
   1.113 +     * when sorting smaller arrays.  This change was required for performance.
   1.114 +     */
   1.115 +    private static final int INITIAL_TMP_STORAGE_LENGTH = 256;
   1.116 +
   1.117 +    /**
   1.118 +     * Temp storage for merges.
   1.119 +     */
   1.120 +    private T[] tmp; // Actual runtime type will be Object[], regardless of T
   1.121 +
   1.122 +    /**
   1.123 +     * A stack of pending runs yet to be merged.  Run i starts at
   1.124 +     * address base[i] and extends for len[i] elements.  It's always
   1.125 +     * true (so long as the indices are in bounds) that:
   1.126 +     *
   1.127 +     *     runBase[i] + runLen[i] == runBase[i + 1]
   1.128 +     *
   1.129 +     * so we could cut the storage for this, but it's a minor amount,
   1.130 +     * and keeping all the info explicit simplifies the code.
   1.131 +     */
   1.132 +    private int stackSize = 0;  // Number of pending runs on stack
   1.133 +    private final int[] runBase;
   1.134 +    private final int[] runLen;
   1.135 +
   1.136 +    /**
   1.137 +     * Creates a TimSort instance to maintain the state of an ongoing sort.
   1.138 +     *
   1.139 +     * @param a the array to be sorted
   1.140 +     * @param c the comparator to determine the order of the sort
   1.141 +     */
   1.142 +    private TimSort(T[] a, Comparator<? super T> c) {
   1.143 +        this.a = a;
   1.144 +        this.c = c;
   1.145 +
   1.146 +        // Allocate temp storage (which may be increased later if necessary)
   1.147 +        int len = a.length;
   1.148 +        @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
   1.149 +        T[] newArray = (T[]) new Object[len < 2 * INITIAL_TMP_STORAGE_LENGTH ?
   1.150 +                                        len >>> 1 : INITIAL_TMP_STORAGE_LENGTH];
   1.151 +        tmp = newArray;
   1.152 +
   1.153 +        /*
   1.154 +         * Allocate runs-to-be-merged stack (which cannot be expanded).  The
   1.155 +         * stack length requirements are described in listsort.txt.  The C
   1.156 +         * version always uses the same stack length (85), but this was
   1.157 +         * measured to be too expensive when sorting "mid-sized" arrays (e.g.,
   1.158 +         * 100 elements) in Java.  Therefore, we use smaller (but sufficiently
   1.159 +         * large) stack lengths for smaller arrays.  The "magic numbers" in the
   1.160 +         * computation below must be changed if MIN_MERGE is decreased.  See
   1.161 +         * the MIN_MERGE declaration above for more information.
   1.162 +         */
   1.163 +        int stackLen = (len <    120  ?  5 :
   1.164 +                        len <   1542  ? 10 :
   1.165 +                        len < 119151  ? 19 : 40);
   1.166 +        runBase = new int[stackLen];
   1.167 +        runLen = new int[stackLen];
   1.168 +    }
   1.169 +
   1.170 +    /*
   1.171 +     * The next two methods (which are package private and static) constitute
   1.172 +     * the entire API of this class.  Each of these methods obeys the contract
   1.173 +     * of the public method with the same signature in java.util.Arrays.
   1.174 +     */
   1.175 +
   1.176 +    static <T> void sort(T[] a, Comparator<? super T> c) {
   1.177 +        sort(a, 0, a.length, c);
   1.178 +    }
   1.179 +
   1.180 +    static <T> void sort(T[] a, int lo, int hi, Comparator<? super T> c) {
   1.181 +        if (c == null) {
   1.182 +            Arrays.sort(a, lo, hi);
   1.183 +            return;
   1.184 +        }
   1.185 +
   1.186 +        rangeCheck(a.length, lo, hi);
   1.187 +        int nRemaining  = hi - lo;
   1.188 +        if (nRemaining < 2)
   1.189 +            return;  // Arrays of size 0 and 1 are always sorted
   1.190 +
   1.191 +        // If array is small, do a "mini-TimSort" with no merges
   1.192 +        if (nRemaining < MIN_MERGE) {
   1.193 +            int initRunLen = countRunAndMakeAscending(a, lo, hi, c);
   1.194 +            binarySort(a, lo, hi, lo + initRunLen, c);
   1.195 +            return;
   1.196 +        }
   1.197 +
   1.198 +        /**
   1.199 +         * March over the array once, left to right, finding natural runs,
   1.200 +         * extending short natural runs to minRun elements, and merging runs
   1.201 +         * to maintain stack invariant.
   1.202 +         */
   1.203 +        TimSort<T> ts = new TimSort<>(a, c);
   1.204 +        int minRun = minRunLength(nRemaining);
   1.205 +        do {
   1.206 +            // Identify next run
   1.207 +            int runLen = countRunAndMakeAscending(a, lo, hi, c);
   1.208 +
   1.209 +            // If run is short, extend to min(minRun, nRemaining)
   1.210 +            if (runLen < minRun) {
   1.211 +                int force = nRemaining <= minRun ? nRemaining : minRun;
   1.212 +                binarySort(a, lo, lo + force, lo + runLen, c);
   1.213 +                runLen = force;
   1.214 +            }
   1.215 +
   1.216 +            // Push run onto pending-run stack, and maybe merge
   1.217 +            ts.pushRun(lo, runLen);
   1.218 +            ts.mergeCollapse();
   1.219 +
   1.220 +            // Advance to find next run
   1.221 +            lo += runLen;
   1.222 +            nRemaining -= runLen;
   1.223 +        } while (nRemaining != 0);
   1.224 +
   1.225 +        // Merge all remaining runs to complete sort
   1.226 +        assert lo == hi;
   1.227 +        ts.mergeForceCollapse();
   1.228 +        assert ts.stackSize == 1;
   1.229 +    }
   1.230 +
   1.231 +    /**
   1.232 +     * Sorts the specified portion of the specified array using a binary
   1.233 +     * insertion sort.  This is the best method for sorting small numbers
   1.234 +     * of elements.  It requires O(n log n) compares, but O(n^2) data
   1.235 +     * movement (worst case).
   1.236 +     *
   1.237 +     * If the initial part of the specified range is already sorted,
   1.238 +     * this method can take advantage of it: the method assumes that the
   1.239 +     * elements from index {@code lo}, inclusive, to {@code start},
   1.240 +     * exclusive are already sorted.
   1.241 +     *
   1.242 +     * @param a the array in which a range is to be sorted
   1.243 +     * @param lo the index of the first element in the range to be sorted
   1.244 +     * @param hi the index after the last element in the range to be sorted
   1.245 +     * @param start the index of the first element in the range that is
   1.246 +     *        not already known to be sorted ({@code lo <= start <= hi})
   1.247 +     * @param c comparator to used for the sort
   1.248 +     */
   1.249 +    @SuppressWarnings("fallthrough")
   1.250 +    private static <T> void binarySort(T[] a, int lo, int hi, int start,
   1.251 +                                       Comparator<? super T> c) {
   1.252 +        assert lo <= start && start <= hi;
   1.253 +        if (start == lo)
   1.254 +            start++;
   1.255 +        for ( ; start < hi; start++) {
   1.256 +            T pivot = a[start];
   1.257 +
   1.258 +            // Set left (and right) to the index where a[start] (pivot) belongs
   1.259 +            int left = lo;
   1.260 +            int right = start;
   1.261 +            assert left <= right;
   1.262 +            /*
   1.263 +             * Invariants:
   1.264 +             *   pivot >= all in [lo, left).
   1.265 +             *   pivot <  all in [right, start).
   1.266 +             */
   1.267 +            while (left < right) {
   1.268 +                int mid = (left + right) >>> 1;
   1.269 +                if (c.compare(pivot, a[mid]) < 0)
   1.270 +                    right = mid;
   1.271 +                else
   1.272 +                    left = mid + 1;
   1.273 +            }
   1.274 +            assert left == right;
   1.275 +
   1.276 +            /*
   1.277 +             * The invariants still hold: pivot >= all in [lo, left) and
   1.278 +             * pivot < all in [left, start), so pivot belongs at left.  Note
   1.279 +             * that if there are elements equal to pivot, left points to the
   1.280 +             * first slot after them -- that's why this sort is stable.
   1.281 +             * Slide elements over to make room for pivot.
   1.282 +             */
   1.283 +            int n = start - left;  // The number of elements to move
   1.284 +            // Switch is just an optimization for arraycopy in default case
   1.285 +            switch (n) {
   1.286 +                case 2:  a[left + 2] = a[left + 1];
   1.287 +                case 1:  a[left + 1] = a[left];
   1.288 +                         break;
   1.289 +                default: System.arraycopy(a, left, a, left + 1, n);
   1.290 +            }
   1.291 +            a[left] = pivot;
   1.292 +        }
   1.293 +    }
   1.294 +
   1.295 +    /**
   1.296 +     * Returns the length of the run beginning at the specified position in
   1.297 +     * the specified array and reverses the run if it is descending (ensuring
   1.298 +     * that the run will always be ascending when the method returns).
   1.299 +     *
   1.300 +     * A run is the longest ascending sequence with:
   1.301 +     *
   1.302 +     *    a[lo] <= a[lo + 1] <= a[lo + 2] <= ...
   1.303 +     *
   1.304 +     * or the longest descending sequence with:
   1.305 +     *
   1.306 +     *    a[lo] >  a[lo + 1] >  a[lo + 2] >  ...
   1.307 +     *
   1.308 +     * For its intended use in a stable mergesort, the strictness of the
   1.309 +     * definition of "descending" is needed so that the call can safely
   1.310 +     * reverse a descending sequence without violating stability.
   1.311 +     *
   1.312 +     * @param a the array in which a run is to be counted and possibly reversed
   1.313 +     * @param lo index of the first element in the run
   1.314 +     * @param hi index after the last element that may be contained in the run.
   1.315 +              It is required that {@code lo < hi}.
   1.316 +     * @param c the comparator to used for the sort
   1.317 +     * @return  the length of the run beginning at the specified position in
   1.318 +     *          the specified array
   1.319 +     */
   1.320 +    private static <T> int countRunAndMakeAscending(T[] a, int lo, int hi,
   1.321 +                                                    Comparator<? super T> c) {
   1.322 +        assert lo < hi;
   1.323 +        int runHi = lo + 1;
   1.324 +        if (runHi == hi)
   1.325 +            return 1;
   1.326 +
   1.327 +        // Find end of run, and reverse range if descending
   1.328 +        if (c.compare(a[runHi++], a[lo]) < 0) { // Descending
   1.329 +            while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0)
   1.330 +                runHi++;
   1.331 +            reverseRange(a, lo, runHi);
   1.332 +        } else {                              // Ascending
   1.333 +            while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0)
   1.334 +                runHi++;
   1.335 +        }
   1.336 +
   1.337 +        return runHi - lo;
   1.338 +    }
   1.339 +
   1.340 +    /**
   1.341 +     * Reverse the specified range of the specified array.
   1.342 +     *
   1.343 +     * @param a the array in which a range is to be reversed
   1.344 +     * @param lo the index of the first element in the range to be reversed
   1.345 +     * @param hi the index after the last element in the range to be reversed
   1.346 +     */
   1.347 +    private static void reverseRange(Object[] a, int lo, int hi) {
   1.348 +        hi--;
   1.349 +        while (lo < hi) {
   1.350 +            Object t = a[lo];
   1.351 +            a[lo++] = a[hi];
   1.352 +            a[hi--] = t;
   1.353 +        }
   1.354 +    }
   1.355 +
   1.356 +    /**
   1.357 +     * Returns the minimum acceptable run length for an array of the specified
   1.358 +     * length. Natural runs shorter than this will be extended with
   1.359 +     * {@link #binarySort}.
   1.360 +     *
   1.361 +     * Roughly speaking, the computation is:
   1.362 +     *
   1.363 +     *  If n < MIN_MERGE, return n (it's too small to bother with fancy stuff).
   1.364 +     *  Else if n is an exact power of 2, return MIN_MERGE/2.
   1.365 +     *  Else return an int k, MIN_MERGE/2 <= k <= MIN_MERGE, such that n/k
   1.366 +     *   is close to, but strictly less than, an exact power of 2.
   1.367 +     *
   1.368 +     * For the rationale, see listsort.txt.
   1.369 +     *
   1.370 +     * @param n the length of the array to be sorted
   1.371 +     * @return the length of the minimum run to be merged
   1.372 +     */
   1.373 +    private static int minRunLength(int n) {
   1.374 +        assert n >= 0;
   1.375 +        int r = 0;      // Becomes 1 if any 1 bits are shifted off
   1.376 +        while (n >= MIN_MERGE) {
   1.377 +            r |= (n & 1);
   1.378 +            n >>= 1;
   1.379 +        }
   1.380 +        return n + r;
   1.381 +    }
   1.382 +
   1.383 +    /**
   1.384 +     * Pushes the specified run onto the pending-run stack.
   1.385 +     *
   1.386 +     * @param runBase index of the first element in the run
   1.387 +     * @param runLen  the number of elements in the run
   1.388 +     */
   1.389 +    private void pushRun(int runBase, int runLen) {
   1.390 +        this.runBase[stackSize] = runBase;
   1.391 +        this.runLen[stackSize] = runLen;
   1.392 +        stackSize++;
   1.393 +    }
   1.394 +
   1.395 +    /**
   1.396 +     * Examines the stack of runs waiting to be merged and merges adjacent runs
   1.397 +     * until the stack invariants are reestablished:
   1.398 +     *
   1.399 +     *     1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1]
   1.400 +     *     2. runLen[i - 2] > runLen[i - 1]
   1.401 +     *
   1.402 +     * This method is called each time a new run is pushed onto the stack,
   1.403 +     * so the invariants are guaranteed to hold for i < stackSize upon
   1.404 +     * entry to the method.
   1.405 +     */
   1.406 +    private void mergeCollapse() {
   1.407 +        while (stackSize > 1) {
   1.408 +            int n = stackSize - 2;
   1.409 +            if (n > 0 && runLen[n-1] <= runLen[n] + runLen[n+1]) {
   1.410 +                if (runLen[n - 1] < runLen[n + 1])
   1.411 +                    n--;
   1.412 +                mergeAt(n);
   1.413 +            } else if (runLen[n] <= runLen[n + 1]) {
   1.414 +                mergeAt(n);
   1.415 +            } else {
   1.416 +                break; // Invariant is established
   1.417 +            }
   1.418 +        }
   1.419 +    }
   1.420 +
   1.421 +    /**
   1.422 +     * Merges all runs on the stack until only one remains.  This method is
   1.423 +     * called once, to complete the sort.
   1.424 +     */
   1.425 +    private void mergeForceCollapse() {
   1.426 +        while (stackSize > 1) {
   1.427 +            int n = stackSize - 2;
   1.428 +            if (n > 0 && runLen[n - 1] < runLen[n + 1])
   1.429 +                n--;
   1.430 +            mergeAt(n);
   1.431 +        }
   1.432 +    }
   1.433 +
   1.434 +    /**
   1.435 +     * Merges the two runs at stack indices i and i+1.  Run i must be
   1.436 +     * the penultimate or antepenultimate run on the stack.  In other words,
   1.437 +     * i must be equal to stackSize-2 or stackSize-3.
   1.438 +     *
   1.439 +     * @param i stack index of the first of the two runs to merge
   1.440 +     */
   1.441 +    private void mergeAt(int i) {
   1.442 +        assert stackSize >= 2;
   1.443 +        assert i >= 0;
   1.444 +        assert i == stackSize - 2 || i == stackSize - 3;
   1.445 +
   1.446 +        int base1 = runBase[i];
   1.447 +        int len1 = runLen[i];
   1.448 +        int base2 = runBase[i + 1];
   1.449 +        int len2 = runLen[i + 1];
   1.450 +        assert len1 > 0 && len2 > 0;
   1.451 +        assert base1 + len1 == base2;
   1.452 +
   1.453 +        /*
   1.454 +         * Record the length of the combined runs; if i is the 3rd-last
   1.455 +         * run now, also slide over the last run (which isn't involved
   1.456 +         * in this merge).  The current run (i+1) goes away in any case.
   1.457 +         */
   1.458 +        runLen[i] = len1 + len2;
   1.459 +        if (i == stackSize - 3) {
   1.460 +            runBase[i + 1] = runBase[i + 2];
   1.461 +            runLen[i + 1] = runLen[i + 2];
   1.462 +        }
   1.463 +        stackSize--;
   1.464 +
   1.465 +        /*
   1.466 +         * Find where the first element of run2 goes in run1. Prior elements
   1.467 +         * in run1 can be ignored (because they're already in place).
   1.468 +         */
   1.469 +        int k = gallopRight(a[base2], a, base1, len1, 0, c);
   1.470 +        assert k >= 0;
   1.471 +        base1 += k;
   1.472 +        len1 -= k;
   1.473 +        if (len1 == 0)
   1.474 +            return;
   1.475 +
   1.476 +        /*
   1.477 +         * Find where the last element of run1 goes in run2. Subsequent elements
   1.478 +         * in run2 can be ignored (because they're already in place).
   1.479 +         */
   1.480 +        len2 = gallopLeft(a[base1 + len1 - 1], a, base2, len2, len2 - 1, c);
   1.481 +        assert len2 >= 0;
   1.482 +        if (len2 == 0)
   1.483 +            return;
   1.484 +
   1.485 +        // Merge remaining runs, using tmp array with min(len1, len2) elements
   1.486 +        if (len1 <= len2)
   1.487 +            mergeLo(base1, len1, base2, len2);
   1.488 +        else
   1.489 +            mergeHi(base1, len1, base2, len2);
   1.490 +    }
   1.491 +
   1.492 +    /**
   1.493 +     * Locates the position at which to insert the specified key into the
   1.494 +     * specified sorted range; if the range contains an element equal to key,
   1.495 +     * returns the index of the leftmost equal element.
   1.496 +     *
   1.497 +     * @param key the key whose insertion point to search for
   1.498 +     * @param a the array in which to search
   1.499 +     * @param base the index of the first element in the range
   1.500 +     * @param len the length of the range; must be > 0
   1.501 +     * @param hint the index at which to begin the search, 0 <= hint < n.
   1.502 +     *     The closer hint is to the result, the faster this method will run.
   1.503 +     * @param c the comparator used to order the range, and to search
   1.504 +     * @return the int k,  0 <= k <= n such that a[b + k - 1] < key <= a[b + k],
   1.505 +     *    pretending that a[b - 1] is minus infinity and a[b + n] is infinity.
   1.506 +     *    In other words, key belongs at index b + k; or in other words,
   1.507 +     *    the first k elements of a should precede key, and the last n - k
   1.508 +     *    should follow it.
   1.509 +     */
   1.510 +    private static <T> int gallopLeft(T key, T[] a, int base, int len, int hint,
   1.511 +                                      Comparator<? super T> c) {
   1.512 +        assert len > 0 && hint >= 0 && hint < len;
   1.513 +        int lastOfs = 0;
   1.514 +        int ofs = 1;
   1.515 +        if (c.compare(key, a[base + hint]) > 0) {
   1.516 +            // Gallop right until a[base+hint+lastOfs] < key <= a[base+hint+ofs]
   1.517 +            int maxOfs = len - hint;
   1.518 +            while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) > 0) {
   1.519 +                lastOfs = ofs;
   1.520 +                ofs = (ofs << 1) + 1;
   1.521 +                if (ofs <= 0)   // int overflow
   1.522 +                    ofs = maxOfs;
   1.523 +            }
   1.524 +            if (ofs > maxOfs)
   1.525 +                ofs = maxOfs;
   1.526 +
   1.527 +            // Make offsets relative to base
   1.528 +            lastOfs += hint;
   1.529 +            ofs += hint;
   1.530 +        } else { // key <= a[base + hint]
   1.531 +            // Gallop left until a[base+hint-ofs] < key <= a[base+hint-lastOfs]
   1.532 +            final int maxOfs = hint + 1;
   1.533 +            while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) <= 0) {
   1.534 +                lastOfs = ofs;
   1.535 +                ofs = (ofs << 1) + 1;
   1.536 +                if (ofs <= 0)   // int overflow
   1.537 +                    ofs = maxOfs;
   1.538 +            }
   1.539 +            if (ofs > maxOfs)
   1.540 +                ofs = maxOfs;
   1.541 +
   1.542 +            // Make offsets relative to base
   1.543 +            int tmp = lastOfs;
   1.544 +            lastOfs = hint - ofs;
   1.545 +            ofs = hint - tmp;
   1.546 +        }
   1.547 +        assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
   1.548 +
   1.549 +        /*
   1.550 +         * Now a[base+lastOfs] < key <= a[base+ofs], so key belongs somewhere
   1.551 +         * to the right of lastOfs but no farther right than ofs.  Do a binary
   1.552 +         * search, with invariant a[base + lastOfs - 1] < key <= a[base + ofs].
   1.553 +         */
   1.554 +        lastOfs++;
   1.555 +        while (lastOfs < ofs) {
   1.556 +            int m = lastOfs + ((ofs - lastOfs) >>> 1);
   1.557 +
   1.558 +            if (c.compare(key, a[base + m]) > 0)
   1.559 +                lastOfs = m + 1;  // a[base + m] < key
   1.560 +            else
   1.561 +                ofs = m;          // key <= a[base + m]
   1.562 +        }
   1.563 +        assert lastOfs == ofs;    // so a[base + ofs - 1] < key <= a[base + ofs]
   1.564 +        return ofs;
   1.565 +    }
   1.566 +
   1.567 +    /**
   1.568 +     * Like gallopLeft, except that if the range contains an element equal to
   1.569 +     * key, gallopRight returns the index after the rightmost equal element.
   1.570 +     *
   1.571 +     * @param key the key whose insertion point to search for
   1.572 +     * @param a the array in which to search
   1.573 +     * @param base the index of the first element in the range
   1.574 +     * @param len the length of the range; must be > 0
   1.575 +     * @param hint the index at which to begin the search, 0 <= hint < n.
   1.576 +     *     The closer hint is to the result, the faster this method will run.
   1.577 +     * @param c the comparator used to order the range, and to search
   1.578 +     * @return the int k,  0 <= k <= n such that a[b + k - 1] <= key < a[b + k]
   1.579 +     */
   1.580 +    private static <T> int gallopRight(T key, T[] a, int base, int len,
   1.581 +                                       int hint, Comparator<? super T> c) {
   1.582 +        assert len > 0 && hint >= 0 && hint < len;
   1.583 +
   1.584 +        int ofs = 1;
   1.585 +        int lastOfs = 0;
   1.586 +        if (c.compare(key, a[base + hint]) < 0) {
   1.587 +            // Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs]
   1.588 +            int maxOfs = hint + 1;
   1.589 +            while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) < 0) {
   1.590 +                lastOfs = ofs;
   1.591 +                ofs = (ofs << 1) + 1;
   1.592 +                if (ofs <= 0)   // int overflow
   1.593 +                    ofs = maxOfs;
   1.594 +            }
   1.595 +            if (ofs > maxOfs)
   1.596 +                ofs = maxOfs;
   1.597 +
   1.598 +            // Make offsets relative to b
   1.599 +            int tmp = lastOfs;
   1.600 +            lastOfs = hint - ofs;
   1.601 +            ofs = hint - tmp;
   1.602 +        } else { // a[b + hint] <= key
   1.603 +            // Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs]
   1.604 +            int maxOfs = len - hint;
   1.605 +            while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) >= 0) {
   1.606 +                lastOfs = ofs;
   1.607 +                ofs = (ofs << 1) + 1;
   1.608 +                if (ofs <= 0)   // int overflow
   1.609 +                    ofs = maxOfs;
   1.610 +            }
   1.611 +            if (ofs > maxOfs)
   1.612 +                ofs = maxOfs;
   1.613 +
   1.614 +            // Make offsets relative to b
   1.615 +            lastOfs += hint;
   1.616 +            ofs += hint;
   1.617 +        }
   1.618 +        assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
   1.619 +
   1.620 +        /*
   1.621 +         * Now a[b + lastOfs] <= key < a[b + ofs], so key belongs somewhere to
   1.622 +         * the right of lastOfs but no farther right than ofs.  Do a binary
   1.623 +         * search, with invariant a[b + lastOfs - 1] <= key < a[b + ofs].
   1.624 +         */
   1.625 +        lastOfs++;
   1.626 +        while (lastOfs < ofs) {
   1.627 +            int m = lastOfs + ((ofs - lastOfs) >>> 1);
   1.628 +
   1.629 +            if (c.compare(key, a[base + m]) < 0)
   1.630 +                ofs = m;          // key < a[b + m]
   1.631 +            else
   1.632 +                lastOfs = m + 1;  // a[b + m] <= key
   1.633 +        }
   1.634 +        assert lastOfs == ofs;    // so a[b + ofs - 1] <= key < a[b + ofs]
   1.635 +        return ofs;
   1.636 +    }
   1.637 +
   1.638 +    /**
   1.639 +     * Merges two adjacent runs in place, in a stable fashion.  The first
   1.640 +     * element of the first run must be greater than the first element of the
   1.641 +     * second run (a[base1] > a[base2]), and the last element of the first run
   1.642 +     * (a[base1 + len1-1]) must be greater than all elements of the second run.
   1.643 +     *
   1.644 +     * For performance, this method should be called only when len1 <= len2;
   1.645 +     * its twin, mergeHi should be called if len1 >= len2.  (Either method
   1.646 +     * may be called if len1 == len2.)
   1.647 +     *
   1.648 +     * @param base1 index of first element in first run to be merged
   1.649 +     * @param len1  length of first run to be merged (must be > 0)
   1.650 +     * @param base2 index of first element in second run to be merged
   1.651 +     *        (must be aBase + aLen)
   1.652 +     * @param len2  length of second run to be merged (must be > 0)
   1.653 +     */
   1.654 +    private void mergeLo(int base1, int len1, int base2, int len2) {
   1.655 +        assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
   1.656 +
   1.657 +        // Copy first run into temp array
   1.658 +        T[] a = this.a; // For performance
   1.659 +        T[] tmp = ensureCapacity(len1);
   1.660 +        System.arraycopy(a, base1, tmp, 0, len1);
   1.661 +
   1.662 +        int cursor1 = 0;       // Indexes into tmp array
   1.663 +        int cursor2 = base2;   // Indexes int a
   1.664 +        int dest = base1;      // Indexes int a
   1.665 +
   1.666 +        // Move first element of second run and deal with degenerate cases
   1.667 +        a[dest++] = a[cursor2++];
   1.668 +        if (--len2 == 0) {
   1.669 +            System.arraycopy(tmp, cursor1, a, dest, len1);
   1.670 +            return;
   1.671 +        }
   1.672 +        if (len1 == 1) {
   1.673 +            System.arraycopy(a, cursor2, a, dest, len2);
   1.674 +            a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge
   1.675 +            return;
   1.676 +        }
   1.677 +
   1.678 +        Comparator<? super T> c = this.c;  // Use local variable for performance
   1.679 +        int minGallop = this.minGallop;    //  "    "       "     "      "
   1.680 +    outer:
   1.681 +        while (true) {
   1.682 +            int count1 = 0; // Number of times in a row that first run won
   1.683 +            int count2 = 0; // Number of times in a row that second run won
   1.684 +
   1.685 +            /*
   1.686 +             * Do the straightforward thing until (if ever) one run starts
   1.687 +             * winning consistently.
   1.688 +             */
   1.689 +            do {
   1.690 +                assert len1 > 1 && len2 > 0;
   1.691 +                if (c.compare(a[cursor2], tmp[cursor1]) < 0) {
   1.692 +                    a[dest++] = a[cursor2++];
   1.693 +                    count2++;
   1.694 +                    count1 = 0;
   1.695 +                    if (--len2 == 0)
   1.696 +                        break outer;
   1.697 +                } else {
   1.698 +                    a[dest++] = tmp[cursor1++];
   1.699 +                    count1++;
   1.700 +                    count2 = 0;
   1.701 +                    if (--len1 == 1)
   1.702 +                        break outer;
   1.703 +                }
   1.704 +            } while ((count1 | count2) < minGallop);
   1.705 +
   1.706 +            /*
   1.707 +             * One run is winning so consistently that galloping may be a
   1.708 +             * huge win. So try that, and continue galloping until (if ever)
   1.709 +             * neither run appears to be winning consistently anymore.
   1.710 +             */
   1.711 +            do {
   1.712 +                assert len1 > 1 && len2 > 0;
   1.713 +                count1 = gallopRight(a[cursor2], tmp, cursor1, len1, 0, c);
   1.714 +                if (count1 != 0) {
   1.715 +                    System.arraycopy(tmp, cursor1, a, dest, count1);
   1.716 +                    dest += count1;
   1.717 +                    cursor1 += count1;
   1.718 +                    len1 -= count1;
   1.719 +                    if (len1 <= 1) // len1 == 1 || len1 == 0
   1.720 +                        break outer;
   1.721 +                }
   1.722 +                a[dest++] = a[cursor2++];
   1.723 +                if (--len2 == 0)
   1.724 +                    break outer;
   1.725 +
   1.726 +                count2 = gallopLeft(tmp[cursor1], a, cursor2, len2, 0, c);
   1.727 +                if (count2 != 0) {
   1.728 +                    System.arraycopy(a, cursor2, a, dest, count2);
   1.729 +                    dest += count2;
   1.730 +                    cursor2 += count2;
   1.731 +                    len2 -= count2;
   1.732 +                    if (len2 == 0)
   1.733 +                        break outer;
   1.734 +                }
   1.735 +                a[dest++] = tmp[cursor1++];
   1.736 +                if (--len1 == 1)
   1.737 +                    break outer;
   1.738 +                minGallop--;
   1.739 +            } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
   1.740 +            if (minGallop < 0)
   1.741 +                minGallop = 0;
   1.742 +            minGallop += 2;  // Penalize for leaving gallop mode
   1.743 +        }  // End of "outer" loop
   1.744 +        this.minGallop = minGallop < 1 ? 1 : minGallop;  // Write back to field
   1.745 +
   1.746 +        if (len1 == 1) {
   1.747 +            assert len2 > 0;
   1.748 +            System.arraycopy(a, cursor2, a, dest, len2);
   1.749 +            a[dest + len2] = tmp[cursor1]; //  Last elt of run 1 to end of merge
   1.750 +        } else if (len1 == 0) {
   1.751 +            throw new IllegalArgumentException(
   1.752 +                "Comparison method violates its general contract!");
   1.753 +        } else {
   1.754 +            assert len2 == 0;
   1.755 +            assert len1 > 1;
   1.756 +            System.arraycopy(tmp, cursor1, a, dest, len1);
   1.757 +        }
   1.758 +    }
   1.759 +
   1.760 +    /**
   1.761 +     * Like mergeLo, except that this method should be called only if
   1.762 +     * len1 >= len2; mergeLo should be called if len1 <= len2.  (Either method
   1.763 +     * may be called if len1 == len2.)
   1.764 +     *
   1.765 +     * @param base1 index of first element in first run to be merged
   1.766 +     * @param len1  length of first run to be merged (must be > 0)
   1.767 +     * @param base2 index of first element in second run to be merged
   1.768 +     *        (must be aBase + aLen)
   1.769 +     * @param len2  length of second run to be merged (must be > 0)
   1.770 +     */
   1.771 +    private void mergeHi(int base1, int len1, int base2, int len2) {
   1.772 +        assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
   1.773 +
   1.774 +        // Copy second run into temp array
   1.775 +        T[] a = this.a; // For performance
   1.776 +        T[] tmp = ensureCapacity(len2);
   1.777 +        System.arraycopy(a, base2, tmp, 0, len2);
   1.778 +
   1.779 +        int cursor1 = base1 + len1 - 1;  // Indexes into a
   1.780 +        int cursor2 = len2 - 1;          // Indexes into tmp array
   1.781 +        int dest = base2 + len2 - 1;     // Indexes into a
   1.782 +
   1.783 +        // Move last element of first run and deal with degenerate cases
   1.784 +        a[dest--] = a[cursor1--];
   1.785 +        if (--len1 == 0) {
   1.786 +            System.arraycopy(tmp, 0, a, dest - (len2 - 1), len2);
   1.787 +            return;
   1.788 +        }
   1.789 +        if (len2 == 1) {
   1.790 +            dest -= len1;
   1.791 +            cursor1 -= len1;
   1.792 +            System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
   1.793 +            a[dest] = tmp[cursor2];
   1.794 +            return;
   1.795 +        }
   1.796 +
   1.797 +        Comparator<? super T> c = this.c;  // Use local variable for performance
   1.798 +        int minGallop = this.minGallop;    //  "    "       "     "      "
   1.799 +    outer:
   1.800 +        while (true) {
   1.801 +            int count1 = 0; // Number of times in a row that first run won
   1.802 +            int count2 = 0; // Number of times in a row that second run won
   1.803 +
   1.804 +            /*
   1.805 +             * Do the straightforward thing until (if ever) one run
   1.806 +             * appears to win consistently.
   1.807 +             */
   1.808 +            do {
   1.809 +                assert len1 > 0 && len2 > 1;
   1.810 +                if (c.compare(tmp[cursor2], a[cursor1]) < 0) {
   1.811 +                    a[dest--] = a[cursor1--];
   1.812 +                    count1++;
   1.813 +                    count2 = 0;
   1.814 +                    if (--len1 == 0)
   1.815 +                        break outer;
   1.816 +                } else {
   1.817 +                    a[dest--] = tmp[cursor2--];
   1.818 +                    count2++;
   1.819 +                    count1 = 0;
   1.820 +                    if (--len2 == 1)
   1.821 +                        break outer;
   1.822 +                }
   1.823 +            } while ((count1 | count2) < minGallop);
   1.824 +
   1.825 +            /*
   1.826 +             * One run is winning so consistently that galloping may be a
   1.827 +             * huge win. So try that, and continue galloping until (if ever)
   1.828 +             * neither run appears to be winning consistently anymore.
   1.829 +             */
   1.830 +            do {
   1.831 +                assert len1 > 0 && len2 > 1;
   1.832 +                count1 = len1 - gallopRight(tmp[cursor2], a, base1, len1, len1 - 1, c);
   1.833 +                if (count1 != 0) {
   1.834 +                    dest -= count1;
   1.835 +                    cursor1 -= count1;
   1.836 +                    len1 -= count1;
   1.837 +                    System.arraycopy(a, cursor1 + 1, a, dest + 1, count1);
   1.838 +                    if (len1 == 0)
   1.839 +                        break outer;
   1.840 +                }
   1.841 +                a[dest--] = tmp[cursor2--];
   1.842 +                if (--len2 == 1)
   1.843 +                    break outer;
   1.844 +
   1.845 +                count2 = len2 - gallopLeft(a[cursor1], tmp, 0, len2, len2 - 1, c);
   1.846 +                if (count2 != 0) {
   1.847 +                    dest -= count2;
   1.848 +                    cursor2 -= count2;
   1.849 +                    len2 -= count2;
   1.850 +                    System.arraycopy(tmp, cursor2 + 1, a, dest + 1, count2);
   1.851 +                    if (len2 <= 1)  // len2 == 1 || len2 == 0
   1.852 +                        break outer;
   1.853 +                }
   1.854 +                a[dest--] = a[cursor1--];
   1.855 +                if (--len1 == 0)
   1.856 +                    break outer;
   1.857 +                minGallop--;
   1.858 +            } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
   1.859 +            if (minGallop < 0)
   1.860 +                minGallop = 0;
   1.861 +            minGallop += 2;  // Penalize for leaving gallop mode
   1.862 +        }  // End of "outer" loop
   1.863 +        this.minGallop = minGallop < 1 ? 1 : minGallop;  // Write back to field
   1.864 +
   1.865 +        if (len2 == 1) {
   1.866 +            assert len1 > 0;
   1.867 +            dest -= len1;
   1.868 +            cursor1 -= len1;
   1.869 +            System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
   1.870 +            a[dest] = tmp[cursor2];  // Move first elt of run2 to front of merge
   1.871 +        } else if (len2 == 0) {
   1.872 +            throw new IllegalArgumentException(
   1.873 +                "Comparison method violates its general contract!");
   1.874 +        } else {
   1.875 +            assert len1 == 0;
   1.876 +            assert len2 > 0;
   1.877 +            System.arraycopy(tmp, 0, a, dest - (len2 - 1), len2);
   1.878 +        }
   1.879 +    }
   1.880 +
   1.881 +    /**
   1.882 +     * Ensures that the external array tmp has at least the specified
   1.883 +     * number of elements, increasing its size if necessary.  The size
   1.884 +     * increases exponentially to ensure amortized linear time complexity.
   1.885 +     *
   1.886 +     * @param minCapacity the minimum required capacity of the tmp array
   1.887 +     * @return tmp, whether or not it grew
   1.888 +     */
   1.889 +    private T[] ensureCapacity(int minCapacity) {
   1.890 +        if (tmp.length < minCapacity) {
   1.891 +            // Compute smallest power of 2 > minCapacity
   1.892 +            int newSize = minCapacity;
   1.893 +            newSize |= newSize >> 1;
   1.894 +            newSize |= newSize >> 2;
   1.895 +            newSize |= newSize >> 4;
   1.896 +            newSize |= newSize >> 8;
   1.897 +            newSize |= newSize >> 16;
   1.898 +            newSize++;
   1.899 +
   1.900 +            if (newSize < 0) // Not bloody likely!
   1.901 +                newSize = minCapacity;
   1.902 +            else
   1.903 +                newSize = Math.min(newSize, a.length >>> 1);
   1.904 +
   1.905 +            @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
   1.906 +            T[] newArray = (T[]) new Object[newSize];
   1.907 +            tmp = newArray;
   1.908 +        }
   1.909 +        return tmp;
   1.910 +    }
   1.911 +
   1.912 +    /**
   1.913 +     * Checks that fromIndex and toIndex are in range, and throws an
   1.914 +     * appropriate exception if they aren't.
   1.915 +     *
   1.916 +     * @param arrayLen the length of the array
   1.917 +     * @param fromIndex the index of the first element of the range
   1.918 +     * @param toIndex the index after the last element of the range
   1.919 +     * @throws IllegalArgumentException if fromIndex > toIndex
   1.920 +     * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
   1.921 +     *         or toIndex > arrayLen
   1.922 +     */
   1.923 +    private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
   1.924 +        if (fromIndex > toIndex)
   1.925 +            throw new IllegalArgumentException("fromIndex(" + fromIndex +
   1.926 +                       ") > toIndex(" + toIndex+")");
   1.927 +        if (fromIndex < 0)
   1.928 +            throw new ArrayIndexOutOfBoundsException(fromIndex);
   1.929 +        if (toIndex > arrayLen)
   1.930 +            throw new ArrayIndexOutOfBoundsException(toIndex);
   1.931 +    }
   1.932 +}