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