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