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