1473N/A/*
1473N/A * Copyright 2009 Google Inc. All Rights Reserved.
1473N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1473N/A *
1473N/A * This code is free software; you can redistribute it and/or modify it
1473N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
1473N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
1473N/A *
1473N/A * This code is distributed in the hope that it will be useful, but WITHOUT
1473N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1473N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1473N/A * version 2 for more details (a copy is included in the LICENSE file that
1473N/A * accompanied this code).
1473N/A *
1473N/A * You should have received a copy of the GNU General Public License version
1473N/A * 2 along with this work; if not, write to the Free Software Foundation,
1473N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1473N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
1473N/A */
1473N/A
1473N/Apackage java.util;
1473N/A
1473N/A/**
1473N/A * A stable, adaptive, iterative mergesort that requires far fewer than
1473N/A * n lg(n) comparisons when running on partially sorted arrays, while
1473N/A * offering performance comparable to a traditional mergesort when run
1473N/A * on random arrays. Like all proper mergesorts, this sort is stable and
1473N/A * runs O(n log n) time (worst case). In the worst case, this sort requires
1473N/A * temporary storage space for n/2 object references; in the best case,
1473N/A * it requires only a small constant amount of space.
1473N/A *
1473N/A * This implementation was adapted from Tim Peters's list sort for
1473N/A * Python, which is described in detail here:
1473N/A *
1473N/A * http://svn.python.org/projects/python/trunk/Objects/listsort.txt
1473N/A *
1473N/A * Tim's C code may be found here:
1473N/A *
1473N/A * http://svn.python.org/projects/python/trunk/Objects/listobject.c
1473N/A *
1473N/A * The underlying techniques are described in this paper (and may have
1473N/A * even earlier origins):
1473N/A *
1473N/A * "Optimistic Sorting and Information Theoretic Complexity"
1473N/A * Peter McIlroy
1473N/A * SODA (Fourth Annual ACM-SIAM Symposium on Discrete Algorithms),
1473N/A * pp 467-474, Austin, Texas, 25-27 January 1993.
1473N/A *
1473N/A * While the API to this class consists solely of static methods, it is
1473N/A * (privately) instantiable; a TimSort instance holds the state of an ongoing
1473N/A * sort, assuming the input array is large enough to warrant the full-blown
1473N/A * TimSort. Small arrays are sorted in place, using a binary insertion sort.
1473N/A *
1473N/A * @author Josh Bloch
1473N/A */
1473N/Aclass TimSort<T> {
1473N/A /**
1473N/A * This is the minimum sized sequence that will be merged. Shorter
1473N/A * sequences will be lengthened by calling binarySort. If the entire
1473N/A * array is less than this length, no merges will be performed.
1473N/A *
1473N/A * This constant should be a power of two. It was 64 in Tim Peter's C
1473N/A * implementation, but 32 was empirically determined to work better in
1473N/A * this implementation. In the unlikely event that you set this constant
1473N/A * to be a number that's not a power of two, you'll need to change the
1473N/A * {@link #minRunLength} computation.
1473N/A *
1473N/A * If you decrease this constant, you must change the stackLen
1473N/A * computation in the TimSort constructor, or you risk an
1473N/A * ArrayOutOfBounds exception. See listsort.txt for a discussion
1473N/A * of the minimum stack length required as a function of the length
1473N/A * of the array being sorted and the minimum merge sequence length.
1473N/A */
1473N/A private static final int MIN_MERGE = 32;
1473N/A
1473N/A /**
1473N/A * The array being sorted.
1473N/A */
1473N/A private final T[] a;
1473N/A
1473N/A /**
1473N/A * The comparator for this sort.
1473N/A */
1473N/A private final Comparator<? super T> c;
1473N/A
1473N/A /**
1473N/A * When we get into galloping mode, we stay there until both runs win less
1473N/A * often than MIN_GALLOP consecutive times.
1473N/A */
1473N/A private static final int MIN_GALLOP = 7;
1473N/A
1473N/A /**
1473N/A * This controls when we get *into* galloping mode. It is initialized
1473N/A * to MIN_GALLOP. The mergeLo and mergeHi methods nudge it higher for
1473N/A * random data, and lower for highly structured data.
1473N/A */
1473N/A private int minGallop = MIN_GALLOP;
1473N/A
1473N/A /**
1473N/A * Maximum initial size of tmp array, which is used for merging. The array
1473N/A * can grow to accommodate demand.
1473N/A *
1473N/A * Unlike Tim's original C version, we do not allocate this much storage
1473N/A * when sorting smaller arrays. This change was required for performance.
1473N/A */
1473N/A private static final int INITIAL_TMP_STORAGE_LENGTH = 256;
1473N/A
1473N/A /**
1473N/A * Temp storage for merges.
1473N/A */
1473N/A private T[] tmp; // Actual runtime type will be Object[], regardless of T
1473N/A
1473N/A /**
1473N/A * A stack of pending runs yet to be merged. Run i starts at
1473N/A * address base[i] and extends for len[i] elements. It's always
1473N/A * true (so long as the indices are in bounds) that:
1473N/A *
1473N/A * runBase[i] + runLen[i] == runBase[i + 1]
1473N/A *
1473N/A * so we could cut the storage for this, but it's a minor amount,
1473N/A * and keeping all the info explicit simplifies the code.
1473N/A */
1473N/A private int stackSize = 0; // Number of pending runs on stack
1473N/A private final int[] runBase;
1473N/A private final int[] runLen;
1473N/A
1473N/A /**
1473N/A * Creates a TimSort instance to maintain the state of an ongoing sort.
1473N/A *
1473N/A * @param a the array to be sorted
1473N/A * @param c the comparator to determine the order of the sort
1473N/A */
1473N/A private TimSort(T[] a, Comparator<? super T> c) {
1473N/A this.a = a;
1473N/A this.c = c;
1473N/A
1473N/A // Allocate temp storage (which may be increased later if necessary)
1473N/A int len = a.length;
1473N/A @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
1473N/A T[] newArray = (T[]) new Object[len < 2 * INITIAL_TMP_STORAGE_LENGTH ?
1473N/A len >>> 1 : INITIAL_TMP_STORAGE_LENGTH];
1473N/A tmp = newArray;
1473N/A
1473N/A /*
1473N/A * Allocate runs-to-be-merged stack (which cannot be expanded). The
1473N/A * stack length requirements are described in listsort.txt. The C
1473N/A * version always uses the same stack length (85), but this was
1473N/A * measured to be too expensive when sorting "mid-sized" arrays (e.g.,
1473N/A * 100 elements) in Java. Therefore, we use smaller (but sufficiently
1473N/A * large) stack lengths for smaller arrays. The "magic numbers" in the
1473N/A * computation below must be changed if MIN_MERGE is decreased. See
1473N/A * the MIN_MERGE declaration above for more information.
1473N/A */
1473N/A int stackLen = (len < 120 ? 5 :
1473N/A len < 1542 ? 10 :
1473N/A len < 119151 ? 19 : 40);
1473N/A runBase = new int[stackLen];
1473N/A runLen = new int[stackLen];
1473N/A }
1473N/A
1473N/A /*
1473N/A * The next two methods (which are package private and static) constitute
1473N/A * the entire API of this class. Each of these methods obeys the contract
1473N/A * of the public method with the same signature in java.util.Arrays.
1473N/A */
1473N/A
1473N/A static <T> void sort(T[] a, Comparator<? super T> c) {
1473N/A sort(a, 0, a.length, c);
1473N/A }
1473N/A
1473N/A static <T> void sort(T[] a, int lo, int hi, Comparator<? super T> c) {
1473N/A if (c == null) {
1473N/A Arrays.sort(a, lo, hi);
1473N/A return;
1473N/A }
1473N/A
1473N/A rangeCheck(a.length, lo, hi);
1473N/A int nRemaining = hi - lo;
1473N/A if (nRemaining < 2)
1473N/A return; // Arrays of size 0 and 1 are always sorted
1473N/A
1473N/A // If array is small, do a "mini-TimSort" with no merges
1473N/A if (nRemaining < MIN_MERGE) {
1473N/A int initRunLen = countRunAndMakeAscending(a, lo, hi, c);
1473N/A binarySort(a, lo, hi, lo + initRunLen, c);
1473N/A return;
1473N/A }
1473N/A
1473N/A /**
1473N/A * March over the array once, left to right, finding natural runs,
1473N/A * extending short natural runs to minRun elements, and merging runs
1473N/A * to maintain stack invariant.
1473N/A */
3323N/A TimSort<T> ts = new TimSort<>(a, c);
1473N/A int minRun = minRunLength(nRemaining);
1473N/A do {
1473N/A // Identify next run
1473N/A int runLen = countRunAndMakeAscending(a, lo, hi, c);
1473N/A
1473N/A // If run is short, extend to min(minRun, nRemaining)
1473N/A if (runLen < minRun) {
1473N/A int force = nRemaining <= minRun ? nRemaining : minRun;
1473N/A binarySort(a, lo, lo + force, lo + runLen, c);
1473N/A runLen = force;
1473N/A }
1473N/A
1473N/A // Push run onto pending-run stack, and maybe merge
1473N/A ts.pushRun(lo, runLen);
1473N/A ts.mergeCollapse();
1473N/A
1473N/A // Advance to find next run
1473N/A lo += runLen;
1473N/A nRemaining -= runLen;
1473N/A } while (nRemaining != 0);
1473N/A
1473N/A // Merge all remaining runs to complete sort
1473N/A assert lo == hi;
1473N/A ts.mergeForceCollapse();
1473N/A assert ts.stackSize == 1;
1473N/A }
1473N/A
1473N/A /**
1473N/A * Sorts the specified portion of the specified array using a binary
1473N/A * insertion sort. This is the best method for sorting small numbers
1473N/A * of elements. It requires O(n log n) compares, but O(n^2) data
1473N/A * movement (worst case).
1473N/A *
1473N/A * If the initial part of the specified range is already sorted,
1473N/A * this method can take advantage of it: the method assumes that the
1473N/A * elements from index {@code lo}, inclusive, to {@code start},
1473N/A * exclusive are already sorted.
1473N/A *
1473N/A * @param a the array in which a range is to be sorted
1473N/A * @param lo the index of the first element in the range to be sorted
1473N/A * @param hi the index after the last element in the range to be sorted
1473N/A * @param start the index of the first element in the range that is
3203N/A * not already known to be sorted ({@code lo <= start <= hi})
1473N/A * @param c comparator to used for the sort
1473N/A */
1473N/A @SuppressWarnings("fallthrough")
1473N/A private static <T> void binarySort(T[] a, int lo, int hi, int start,
1473N/A Comparator<? super T> c) {
1473N/A assert lo <= start && start <= hi;
1473N/A if (start == lo)
1473N/A start++;
1473N/A for ( ; start < hi; start++) {
1473N/A T pivot = a[start];
1473N/A
1473N/A // Set left (and right) to the index where a[start] (pivot) belongs
1473N/A int left = lo;
1473N/A int right = start;
1473N/A assert left <= right;
1473N/A /*
1473N/A * Invariants:
1473N/A * pivot >= all in [lo, left).
1473N/A * pivot < all in [right, start).
1473N/A */
1473N/A while (left < right) {
1473N/A int mid = (left + right) >>> 1;
1473N/A if (c.compare(pivot, a[mid]) < 0)
1473N/A right = mid;
1473N/A else
1473N/A left = mid + 1;
1473N/A }
1473N/A assert left == right;
1473N/A
1473N/A /*
1473N/A * The invariants still hold: pivot >= all in [lo, left) and
1473N/A * pivot < all in [left, start), so pivot belongs at left. Note
1473N/A * that if there are elements equal to pivot, left points to the
1473N/A * first slot after them -- that's why this sort is stable.
3880N/A * Slide elements over to make room for pivot.
1473N/A */
1473N/A int n = start - left; // The number of elements to move
1473N/A // Switch is just an optimization for arraycopy in default case
3203N/A switch (n) {
1473N/A case 2: a[left + 2] = a[left + 1];
1473N/A case 1: a[left + 1] = a[left];
1473N/A break;
1473N/A default: System.arraycopy(a, left, a, left + 1, n);
1473N/A }
1473N/A a[left] = pivot;
1473N/A }
1473N/A }
1473N/A
1473N/A /**
1473N/A * Returns the length of the run beginning at the specified position in
1473N/A * the specified array and reverses the run if it is descending (ensuring
1473N/A * that the run will always be ascending when the method returns).
1473N/A *
1473N/A * A run is the longest ascending sequence with:
1473N/A *
1473N/A * a[lo] <= a[lo + 1] <= a[lo + 2] <= ...
1473N/A *
1473N/A * or the longest descending sequence with:
1473N/A *
1473N/A * a[lo] > a[lo + 1] > a[lo + 2] > ...
1473N/A *
1473N/A * For its intended use in a stable mergesort, the strictness of the
1473N/A * definition of "descending" is needed so that the call can safely
1473N/A * reverse a descending sequence without violating stability.
1473N/A *
1473N/A * @param a the array in which a run is to be counted and possibly reversed
1473N/A * @param lo index of the first element in the run
1473N/A * @param hi index after the last element that may be contained in the run.
3203N/A It is required that {@code lo < hi}.
1473N/A * @param c the comparator to used for the sort
1473N/A * @return the length of the run beginning at the specified position in
1473N/A * the specified array
1473N/A */
1473N/A private static <T> int countRunAndMakeAscending(T[] a, int lo, int hi,
1473N/A Comparator<? super T> c) {
1473N/A assert lo < hi;
1473N/A int runHi = lo + 1;
1473N/A if (runHi == hi)
1473N/A return 1;
1473N/A
1473N/A // Find end of run, and reverse range if descending
1473N/A if (c.compare(a[runHi++], a[lo]) < 0) { // Descending
3203N/A while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0)
1473N/A runHi++;
1473N/A reverseRange(a, lo, runHi);
1473N/A } else { // Ascending
1473N/A while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0)
1473N/A runHi++;
1473N/A }
1473N/A
1473N/A return runHi - lo;
1473N/A }
1473N/A
1473N/A /**
1473N/A * Reverse the specified range of the specified array.
1473N/A *
1473N/A * @param a the array in which a range is to be reversed
1473N/A * @param lo the index of the first element in the range to be reversed
1473N/A * @param hi the index after the last element in the range to be reversed
1473N/A */
1473N/A private static void reverseRange(Object[] a, int lo, int hi) {
1473N/A hi--;
1473N/A while (lo < hi) {
1473N/A Object t = a[lo];
1473N/A a[lo++] = a[hi];
1473N/A a[hi--] = t;
1473N/A }
1473N/A }
1473N/A
1473N/A /**
1473N/A * Returns the minimum acceptable run length for an array of the specified
1473N/A * length. Natural runs shorter than this will be extended with
1473N/A * {@link #binarySort}.
1473N/A *
1473N/A * Roughly speaking, the computation is:
1473N/A *
1473N/A * If n < MIN_MERGE, return n (it's too small to bother with fancy stuff).
1473N/A * Else if n is an exact power of 2, return MIN_MERGE/2.
1473N/A * Else return an int k, MIN_MERGE/2 <= k <= MIN_MERGE, such that n/k
1473N/A * is close to, but strictly less than, an exact power of 2.
1473N/A *
1473N/A * For the rationale, see listsort.txt.
1473N/A *
1473N/A * @param n the length of the array to be sorted
1473N/A * @return the length of the minimum run to be merged
1473N/A */
1473N/A private static int minRunLength(int n) {
1473N/A assert n >= 0;
1473N/A int r = 0; // Becomes 1 if any 1 bits are shifted off
1473N/A while (n >= MIN_MERGE) {
1473N/A r |= (n & 1);
1473N/A n >>= 1;
1473N/A }
1473N/A return n + r;
1473N/A }
1473N/A
1473N/A /**
1473N/A * Pushes the specified run onto the pending-run stack.
1473N/A *
1473N/A * @param runBase index of the first element in the run
1473N/A * @param runLen the number of elements in the run
1473N/A */
1473N/A private void pushRun(int runBase, int runLen) {
1473N/A this.runBase[stackSize] = runBase;
1473N/A this.runLen[stackSize] = runLen;
1473N/A stackSize++;
1473N/A }
1473N/A
1473N/A /**
1473N/A * Examines the stack of runs waiting to be merged and merges adjacent runs
1473N/A * until the stack invariants are reestablished:
1473N/A *
1473N/A * 1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1]
1473N/A * 2. runLen[i - 2] > runLen[i - 1]
1473N/A *
1473N/A * This method is called each time a new run is pushed onto the stack,
1473N/A * so the invariants are guaranteed to hold for i < stackSize upon
1473N/A * entry to the method.
1473N/A */
1473N/A private void mergeCollapse() {
1473N/A while (stackSize > 1) {
1473N/A int n = stackSize - 2;
1473N/A if (n > 0 && runLen[n-1] <= runLen[n] + runLen[n+1]) {
1473N/A if (runLen[n - 1] < runLen[n + 1])
1473N/A n--;
1473N/A mergeAt(n);
1473N/A } else if (runLen[n] <= runLen[n + 1]) {
1473N/A mergeAt(n);
1473N/A } else {
1473N/A break; // Invariant is established
1473N/A }
1473N/A }
1473N/A }
1473N/A
1473N/A /**
1473N/A * Merges all runs on the stack until only one remains. This method is
1473N/A * called once, to complete the sort.
1473N/A */
1473N/A private void mergeForceCollapse() {
1473N/A while (stackSize > 1) {
1473N/A int n = stackSize - 2;
1473N/A if (n > 0 && runLen[n - 1] < runLen[n + 1])
1473N/A n--;
1473N/A mergeAt(n);
1473N/A }
1473N/A }
1473N/A
1473N/A /**
1473N/A * Merges the two runs at stack indices i and i+1. Run i must be
1473N/A * the penultimate or antepenultimate run on the stack. In other words,
1473N/A * i must be equal to stackSize-2 or stackSize-3.
1473N/A *
1473N/A * @param i stack index of the first of the two runs to merge
1473N/A */
1473N/A private void mergeAt(int i) {
1473N/A assert stackSize >= 2;
1473N/A assert i >= 0;
1473N/A assert i == stackSize - 2 || i == stackSize - 3;
1473N/A
1473N/A int base1 = runBase[i];
1473N/A int len1 = runLen[i];
1473N/A int base2 = runBase[i + 1];
1473N/A int len2 = runLen[i + 1];
1473N/A assert len1 > 0 && len2 > 0;
1473N/A assert base1 + len1 == base2;
1473N/A
1473N/A /*
1473N/A * Record the length of the combined runs; if i is the 3rd-last
1473N/A * run now, also slide over the last run (which isn't involved
1473N/A * in this merge). The current run (i+1) goes away in any case.
1473N/A */
1473N/A runLen[i] = len1 + len2;
1473N/A if (i == stackSize - 3) {
1473N/A runBase[i + 1] = runBase[i + 2];
1473N/A runLen[i + 1] = runLen[i + 2];
1473N/A }
1473N/A stackSize--;
1473N/A
1473N/A /*
1473N/A * Find where the first element of run2 goes in run1. Prior elements
1473N/A * in run1 can be ignored (because they're already in place).
1473N/A */
1473N/A int k = gallopRight(a[base2], a, base1, len1, 0, c);
1473N/A assert k >= 0;
1473N/A base1 += k;
1473N/A len1 -= k;
1473N/A if (len1 == 0)
1473N/A return;
1473N/A
1473N/A /*
1473N/A * Find where the last element of run1 goes in run2. Subsequent elements
1473N/A * in run2 can be ignored (because they're already in place).
1473N/A */
1473N/A len2 = gallopLeft(a[base1 + len1 - 1], a, base2, len2, len2 - 1, c);
1473N/A assert len2 >= 0;
1473N/A if (len2 == 0)
1473N/A return;
1473N/A
1473N/A // Merge remaining runs, using tmp array with min(len1, len2) elements
1473N/A if (len1 <= len2)
1473N/A mergeLo(base1, len1, base2, len2);
1473N/A else
1473N/A mergeHi(base1, len1, base2, len2);
1473N/A }
1473N/A
1473N/A /**
1473N/A * Locates the position at which to insert the specified key into the
1473N/A * specified sorted range; if the range contains an element equal to key,
1473N/A * returns the index of the leftmost equal element.
1473N/A *
1473N/A * @param key the key whose insertion point to search for
1473N/A * @param a the array in which to search
1473N/A * @param base the index of the first element in the range
1473N/A * @param len the length of the range; must be > 0
1473N/A * @param hint the index at which to begin the search, 0 <= hint < n.
1473N/A * The closer hint is to the result, the faster this method will run.
1473N/A * @param c the comparator used to order the range, and to search
1473N/A * @return the int k, 0 <= k <= n such that a[b + k - 1] < key <= a[b + k],
1473N/A * pretending that a[b - 1] is minus infinity and a[b + n] is infinity.
1473N/A * In other words, key belongs at index b + k; or in other words,
1473N/A * the first k elements of a should precede key, and the last n - k
1473N/A * should follow it.
1473N/A */
1473N/A private static <T> int gallopLeft(T key, T[] a, int base, int len, int hint,
1473N/A Comparator<? super T> c) {
1473N/A assert len > 0 && hint >= 0 && hint < len;
1473N/A int lastOfs = 0;
1473N/A int ofs = 1;
1473N/A if (c.compare(key, a[base + hint]) > 0) {
1473N/A // Gallop right until a[base+hint+lastOfs] < key <= a[base+hint+ofs]
1473N/A int maxOfs = len - hint;
1473N/A while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) > 0) {
1473N/A lastOfs = ofs;
1473N/A ofs = (ofs << 1) + 1;
1473N/A if (ofs <= 0) // int overflow
1473N/A ofs = maxOfs;
1473N/A }
1473N/A if (ofs > maxOfs)
1473N/A ofs = maxOfs;
1473N/A
1473N/A // Make offsets relative to base
1473N/A lastOfs += hint;
1473N/A ofs += hint;
1473N/A } else { // key <= a[base + hint]
1473N/A // Gallop left until a[base+hint-ofs] < key <= a[base+hint-lastOfs]
1473N/A final int maxOfs = hint + 1;
1473N/A while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) <= 0) {
1473N/A lastOfs = ofs;
1473N/A ofs = (ofs << 1) + 1;
1473N/A if (ofs <= 0) // int overflow
1473N/A ofs = maxOfs;
1473N/A }
1473N/A if (ofs > maxOfs)
1473N/A ofs = maxOfs;
1473N/A
1473N/A // Make offsets relative to base
1473N/A int tmp = lastOfs;
1473N/A lastOfs = hint - ofs;
1473N/A ofs = hint - tmp;
1473N/A }
1473N/A assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
1473N/A
1473N/A /*
1473N/A * Now a[base+lastOfs] < key <= a[base+ofs], so key belongs somewhere
1473N/A * to the right of lastOfs but no farther right than ofs. Do a binary
1473N/A * search, with invariant a[base + lastOfs - 1] < key <= a[base + ofs].
1473N/A */
1473N/A lastOfs++;
1473N/A while (lastOfs < ofs) {
1473N/A int m = lastOfs + ((ofs - lastOfs) >>> 1);
1473N/A
1473N/A if (c.compare(key, a[base + m]) > 0)
1473N/A lastOfs = m + 1; // a[base + m] < key
1473N/A else
1473N/A ofs = m; // key <= a[base + m]
1473N/A }
1473N/A assert lastOfs == ofs; // so a[base + ofs - 1] < key <= a[base + ofs]
1473N/A return ofs;
1473N/A }
1473N/A
1473N/A /**
1473N/A * Like gallopLeft, except that if the range contains an element equal to
1473N/A * key, gallopRight returns the index after the rightmost equal element.
1473N/A *
1473N/A * @param key the key whose insertion point to search for
1473N/A * @param a the array in which to search
1473N/A * @param base the index of the first element in the range
1473N/A * @param len the length of the range; must be > 0
1473N/A * @param hint the index at which to begin the search, 0 <= hint < n.
1473N/A * The closer hint is to the result, the faster this method will run.
1473N/A * @param c the comparator used to order the range, and to search
1473N/A * @return the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k]
1473N/A */
1473N/A private static <T> int gallopRight(T key, T[] a, int base, int len,
1473N/A int hint, Comparator<? super T> c) {
1473N/A assert len > 0 && hint >= 0 && hint < len;
1473N/A
1473N/A int ofs = 1;
1473N/A int lastOfs = 0;
1473N/A if (c.compare(key, a[base + hint]) < 0) {
1473N/A // Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs]
1473N/A int maxOfs = hint + 1;
1473N/A while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) < 0) {
1473N/A lastOfs = ofs;
1473N/A ofs = (ofs << 1) + 1;
1473N/A if (ofs <= 0) // int overflow
1473N/A ofs = maxOfs;
1473N/A }
1473N/A if (ofs > maxOfs)
1473N/A ofs = maxOfs;
1473N/A
1473N/A // Make offsets relative to b
1473N/A int tmp = lastOfs;
1473N/A lastOfs = hint - ofs;
1473N/A ofs = hint - tmp;
1473N/A } else { // a[b + hint] <= key
1473N/A // Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs]
1473N/A int maxOfs = len - hint;
1473N/A while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) >= 0) {
1473N/A lastOfs = ofs;
1473N/A ofs = (ofs << 1) + 1;
1473N/A if (ofs <= 0) // int overflow
1473N/A ofs = maxOfs;
1473N/A }
1473N/A if (ofs > maxOfs)
1473N/A ofs = maxOfs;
1473N/A
1473N/A // Make offsets relative to b
1473N/A lastOfs += hint;
1473N/A ofs += hint;
1473N/A }
1473N/A assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
1473N/A
1473N/A /*
1473N/A * Now a[b + lastOfs] <= key < a[b + ofs], so key belongs somewhere to
1473N/A * the right of lastOfs but no farther right than ofs. Do a binary
1473N/A * search, with invariant a[b + lastOfs - 1] <= key < a[b + ofs].
1473N/A */
1473N/A lastOfs++;
1473N/A while (lastOfs < ofs) {
1473N/A int m = lastOfs + ((ofs - lastOfs) >>> 1);
1473N/A
1473N/A if (c.compare(key, a[base + m]) < 0)
1473N/A ofs = m; // key < a[b + m]
1473N/A else
1473N/A lastOfs = m + 1; // a[b + m] <= key
1473N/A }
1473N/A assert lastOfs == ofs; // so a[b + ofs - 1] <= key < a[b + ofs]
1473N/A return ofs;
1473N/A }
1473N/A
1473N/A /**
1473N/A * Merges two adjacent runs in place, in a stable fashion. The first
1473N/A * element of the first run must be greater than the first element of the
1473N/A * second run (a[base1] > a[base2]), and the last element of the first run
1473N/A * (a[base1 + len1-1]) must be greater than all elements of the second run.
1473N/A *
1473N/A * For performance, this method should be called only when len1 <= len2;
1473N/A * its twin, mergeHi should be called if len1 >= len2. (Either method
1473N/A * may be called if len1 == len2.)
1473N/A *
1473N/A * @param base1 index of first element in first run to be merged
1473N/A * @param len1 length of first run to be merged (must be > 0)
1473N/A * @param base2 index of first element in second run to be merged
1473N/A * (must be aBase + aLen)
1473N/A * @param len2 length of second run to be merged (must be > 0)
1473N/A */
1473N/A private void mergeLo(int base1, int len1, int base2, int len2) {
1473N/A assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
1473N/A
1473N/A // Copy first run into temp array
1473N/A T[] a = this.a; // For performance
1473N/A T[] tmp = ensureCapacity(len1);
1473N/A System.arraycopy(a, base1, tmp, 0, len1);
1473N/A
1473N/A int cursor1 = 0; // Indexes into tmp array
1473N/A int cursor2 = base2; // Indexes int a
1473N/A int dest = base1; // Indexes int a
1473N/A
1473N/A // Move first element of second run and deal with degenerate cases
1473N/A a[dest++] = a[cursor2++];
1473N/A if (--len2 == 0) {
1473N/A System.arraycopy(tmp, cursor1, a, dest, len1);
1473N/A return;
1473N/A }
1473N/A if (len1 == 1) {
1473N/A System.arraycopy(a, cursor2, a, dest, len2);
1473N/A a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge
1473N/A return;
1473N/A }
1473N/A
1473N/A Comparator<? super T> c = this.c; // Use local variable for performance
1473N/A int minGallop = this.minGallop; // " " " " "
1473N/A outer:
1473N/A while (true) {
1473N/A int count1 = 0; // Number of times in a row that first run won
1473N/A int count2 = 0; // Number of times in a row that second run won
1473N/A
1473N/A /*
1473N/A * Do the straightforward thing until (if ever) one run starts
1473N/A * winning consistently.
1473N/A */
1473N/A do {
1473N/A assert len1 > 1 && len2 > 0;
1473N/A if (c.compare(a[cursor2], tmp[cursor1]) < 0) {
1473N/A a[dest++] = a[cursor2++];
1473N/A count2++;
1473N/A count1 = 0;
1473N/A if (--len2 == 0)
1473N/A break outer;
1473N/A } else {
1473N/A a[dest++] = tmp[cursor1++];
1473N/A count1++;
1473N/A count2 = 0;
1473N/A if (--len1 == 1)
1473N/A break outer;
1473N/A }
1473N/A } while ((count1 | count2) < minGallop);
1473N/A
1473N/A /*
1473N/A * One run is winning so consistently that galloping may be a
1473N/A * huge win. So try that, and continue galloping until (if ever)
1473N/A * neither run appears to be winning consistently anymore.
1473N/A */
1473N/A do {
1473N/A assert len1 > 1 && len2 > 0;
1473N/A count1 = gallopRight(a[cursor2], tmp, cursor1, len1, 0, c);
1473N/A if (count1 != 0) {
1473N/A System.arraycopy(tmp, cursor1, a, dest, count1);
1473N/A dest += count1;
1473N/A cursor1 += count1;
1473N/A len1 -= count1;
1473N/A if (len1 <= 1) // len1 == 1 || len1 == 0
1473N/A break outer;
1473N/A }
1473N/A a[dest++] = a[cursor2++];
1473N/A if (--len2 == 0)
1473N/A break outer;
1473N/A
1473N/A count2 = gallopLeft(tmp[cursor1], a, cursor2, len2, 0, c);
1473N/A if (count2 != 0) {
1473N/A System.arraycopy(a, cursor2, a, dest, count2);
1473N/A dest += count2;
1473N/A cursor2 += count2;
1473N/A len2 -= count2;
1473N/A if (len2 == 0)
1473N/A break outer;
1473N/A }
1473N/A a[dest++] = tmp[cursor1++];
1473N/A if (--len1 == 1)
1473N/A break outer;
1473N/A minGallop--;
1473N/A } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
1473N/A if (minGallop < 0)
1473N/A minGallop = 0;
1473N/A minGallop += 2; // Penalize for leaving gallop mode
1473N/A } // End of "outer" loop
1473N/A this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field
1473N/A
1473N/A if (len1 == 1) {
1473N/A assert len2 > 0;
1473N/A System.arraycopy(a, cursor2, a, dest, len2);
1473N/A a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge
1473N/A } else if (len1 == 0) {
1473N/A throw new IllegalArgumentException(
1473N/A "Comparison method violates its general contract!");
1473N/A } else {
1473N/A assert len2 == 0;
1473N/A assert len1 > 1;
1473N/A System.arraycopy(tmp, cursor1, a, dest, len1);
1473N/A }
1473N/A }
1473N/A
1473N/A /**
1473N/A * Like mergeLo, except that this method should be called only if
1473N/A * len1 >= len2; mergeLo should be called if len1 <= len2. (Either method
1473N/A * may be called if len1 == len2.)
1473N/A *
1473N/A * @param base1 index of first element in first run to be merged
1473N/A * @param len1 length of first run to be merged (must be > 0)
1473N/A * @param base2 index of first element in second run to be merged
1473N/A * (must be aBase + aLen)
1473N/A * @param len2 length of second run to be merged (must be > 0)
1473N/A */
1473N/A private void mergeHi(int base1, int len1, int base2, int len2) {
1473N/A assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
1473N/A
1473N/A // Copy second run into temp array
1473N/A T[] a = this.a; // For performance
1473N/A T[] tmp = ensureCapacity(len2);
1473N/A System.arraycopy(a, base2, tmp, 0, len2);
1473N/A
1473N/A int cursor1 = base1 + len1 - 1; // Indexes into a
1473N/A int cursor2 = len2 - 1; // Indexes into tmp array
1473N/A int dest = base2 + len2 - 1; // Indexes into a
1473N/A
1473N/A // Move last element of first run and deal with degenerate cases
1473N/A a[dest--] = a[cursor1--];
1473N/A if (--len1 == 0) {
1473N/A System.arraycopy(tmp, 0, a, dest - (len2 - 1), len2);
1473N/A return;
1473N/A }
1473N/A if (len2 == 1) {
1473N/A dest -= len1;
1473N/A cursor1 -= len1;
1473N/A System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
1473N/A a[dest] = tmp[cursor2];
1473N/A return;
1473N/A }
1473N/A
1473N/A Comparator<? super T> c = this.c; // Use local variable for performance
1473N/A int minGallop = this.minGallop; // " " " " "
1473N/A outer:
1473N/A while (true) {
1473N/A int count1 = 0; // Number of times in a row that first run won
1473N/A int count2 = 0; // Number of times in a row that second run won
1473N/A
1473N/A /*
1473N/A * Do the straightforward thing until (if ever) one run
1473N/A * appears to win consistently.
1473N/A */
1473N/A do {
1473N/A assert len1 > 0 && len2 > 1;
1473N/A if (c.compare(tmp[cursor2], a[cursor1]) < 0) {
1473N/A a[dest--] = a[cursor1--];
1473N/A count1++;
1473N/A count2 = 0;
1473N/A if (--len1 == 0)
1473N/A break outer;
1473N/A } else {
1473N/A a[dest--] = tmp[cursor2--];
1473N/A count2++;
1473N/A count1 = 0;
1473N/A if (--len2 == 1)
1473N/A break outer;
1473N/A }
1473N/A } while ((count1 | count2) < minGallop);
1473N/A
1473N/A /*
1473N/A * One run is winning so consistently that galloping may be a
1473N/A * huge win. So try that, and continue galloping until (if ever)
1473N/A * neither run appears to be winning consistently anymore.
1473N/A */
1473N/A do {
1473N/A assert len1 > 0 && len2 > 1;
1473N/A count1 = len1 - gallopRight(tmp[cursor2], a, base1, len1, len1 - 1, c);
1473N/A if (count1 != 0) {
1473N/A dest -= count1;
1473N/A cursor1 -= count1;
1473N/A len1 -= count1;
1473N/A System.arraycopy(a, cursor1 + 1, a, dest + 1, count1);
1473N/A if (len1 == 0)
1473N/A break outer;
1473N/A }
1473N/A a[dest--] = tmp[cursor2--];
1473N/A if (--len2 == 1)
1473N/A break outer;
1473N/A
1473N/A count2 = len2 - gallopLeft(a[cursor1], tmp, 0, len2, len2 - 1, c);
1473N/A if (count2 != 0) {
1473N/A dest -= count2;
1473N/A cursor2 -= count2;
1473N/A len2 -= count2;
1473N/A System.arraycopy(tmp, cursor2 + 1, a, dest + 1, count2);
1473N/A if (len2 <= 1) // len2 == 1 || len2 == 0
1473N/A break outer;
1473N/A }
1473N/A a[dest--] = a[cursor1--];
1473N/A if (--len1 == 0)
1473N/A break outer;
1473N/A minGallop--;
1473N/A } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
1473N/A if (minGallop < 0)
1473N/A minGallop = 0;
1473N/A minGallop += 2; // Penalize for leaving gallop mode
1473N/A } // End of "outer" loop
1473N/A this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field
1473N/A
1473N/A if (len2 == 1) {
1473N/A assert len1 > 0;
1473N/A dest -= len1;
1473N/A cursor1 -= len1;
1473N/A System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
1473N/A a[dest] = tmp[cursor2]; // Move first elt of run2 to front of merge
1473N/A } else if (len2 == 0) {
1473N/A throw new IllegalArgumentException(
1473N/A "Comparison method violates its general contract!");
1473N/A } else {
1473N/A assert len1 == 0;
1473N/A assert len2 > 0;
1473N/A System.arraycopy(tmp, 0, a, dest - (len2 - 1), len2);
1473N/A }
1473N/A }
1473N/A
1473N/A /**
1473N/A * Ensures that the external array tmp has at least the specified
1473N/A * number of elements, increasing its size if necessary. The size
1473N/A * increases exponentially to ensure amortized linear time complexity.
1473N/A *
1473N/A * @param minCapacity the minimum required capacity of the tmp array
1473N/A * @return tmp, whether or not it grew
1473N/A */
1473N/A private T[] ensureCapacity(int minCapacity) {
1473N/A if (tmp.length < minCapacity) {
1473N/A // Compute smallest power of 2 > minCapacity
1473N/A int newSize = minCapacity;
1473N/A newSize |= newSize >> 1;
1473N/A newSize |= newSize >> 2;
1473N/A newSize |= newSize >> 4;
1473N/A newSize |= newSize >> 8;
1473N/A newSize |= newSize >> 16;
1473N/A newSize++;
1473N/A
1473N/A if (newSize < 0) // Not bloody likely!
1473N/A newSize = minCapacity;
1473N/A else
1473N/A newSize = Math.min(newSize, a.length >>> 1);
1473N/A
1473N/A @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
1473N/A T[] newArray = (T[]) new Object[newSize];
1473N/A tmp = newArray;
1473N/A }
1473N/A return tmp;
1473N/A }
1473N/A
1473N/A /**
1473N/A * Checks that fromIndex and toIndex are in range, and throws an
1473N/A * appropriate exception if they aren't.
1473N/A *
1473N/A * @param arrayLen the length of the array
1473N/A * @param fromIndex the index of the first element of the range
1473N/A * @param toIndex the index after the last element of the range
1473N/A * @throws IllegalArgumentException if fromIndex > toIndex
1473N/A * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
1473N/A * or toIndex > arrayLen
1473N/A */
1473N/A private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
1473N/A if (fromIndex > toIndex)
1473N/A throw new IllegalArgumentException("fromIndex(" + fromIndex +
1473N/A ") > toIndex(" + toIndex+")");
1473N/A if (fromIndex < 0)
1473N/A throw new ArrayIndexOutOfBoundsException(fromIndex);
1473N/A if (toIndex > arrayLen)
1473N/A throw new ArrayIndexOutOfBoundsException(toIndex);
1473N/A }
1473N/A}