2 * Copyright 2009 Google Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
28 import org.apidesign.bck2brwsr.emul.lang.System;
31 * A stable, adaptive, iterative mergesort that requires far fewer than
32 * n lg(n) comparisons when running on partially sorted arrays, while
33 * offering performance comparable to a traditional mergesort when run
34 * on random arrays. Like all proper mergesorts, this sort is stable and
35 * runs O(n log n) time (worst case). In the worst case, this sort requires
36 * temporary storage space for n/2 object references; in the best case,
37 * it requires only a small constant amount of space.
39 * This implementation was adapted from Tim Peters's list sort for
40 * Python, which is described in detail here:
42 * http://svn.python.org/projects/python/trunk/Objects/listsort.txt
44 * Tim's C code may be found here:
46 * http://svn.python.org/projects/python/trunk/Objects/listobject.c
48 * The underlying techniques are described in this paper (and may have
49 * even earlier origins):
51 * "Optimistic Sorting and Information Theoretic Complexity"
53 * SODA (Fourth Annual ACM-SIAM Symposium on Discrete Algorithms),
54 * pp 467-474, Austin, Texas, 25-27 January 1993.
56 * While the API to this class consists solely of static methods, it is
57 * (privately) instantiable; a TimSort instance holds the state of an ongoing
58 * sort, assuming the input array is large enough to warrant the full-blown
59 * TimSort. Small arrays are sorted in place, using a binary insertion sort.
65 * This is the minimum sized sequence that will be merged. Shorter
66 * sequences will be lengthened by calling binarySort. If the entire
67 * array is less than this length, no merges will be performed.
69 * This constant should be a power of two. It was 64 in Tim Peter's C
70 * implementation, but 32 was empirically determined to work better in
71 * this implementation. In the unlikely event that you set this constant
72 * to be a number that's not a power of two, you'll need to change the
73 * {@link #minRunLength} computation.
75 * If you decrease this constant, you must change the stackLen
76 * computation in the TimSort constructor, or you risk an
77 * ArrayOutOfBounds exception. See listsort.txt for a discussion
78 * of the minimum stack length required as a function of the length
79 * of the array being sorted and the minimum merge sequence length.
81 private static final int MIN_MERGE = 32;
84 * The array being sorted.
89 * The comparator for this sort.
91 private final Comparator<? super T> c;
94 * When we get into galloping mode, we stay there until both runs win less
95 * often than MIN_GALLOP consecutive times.
97 private static final int MIN_GALLOP = 7;
100 * This controls when we get *into* galloping mode. It is initialized
101 * to MIN_GALLOP. The mergeLo and mergeHi methods nudge it higher for
102 * random data, and lower for highly structured data.
104 private int minGallop = MIN_GALLOP;
107 * Maximum initial size of tmp array, which is used for merging. The array
108 * can grow to accommodate demand.
110 * Unlike Tim's original C version, we do not allocate this much storage
111 * when sorting smaller arrays. This change was required for performance.
113 private static final int INITIAL_TMP_STORAGE_LENGTH = 256;
116 * Temp storage for merges.
118 private T[] tmp; // Actual runtime type will be Object[], regardless of T
121 * A stack of pending runs yet to be merged. Run i starts at
122 * address base[i] and extends for len[i] elements. It's always
123 * true (so long as the indices are in bounds) that:
125 * runBase[i] + runLen[i] == runBase[i + 1]
127 * so we could cut the storage for this, but it's a minor amount,
128 * and keeping all the info explicit simplifies the code.
130 private int stackSize = 0; // Number of pending runs on stack
131 private final int[] runBase;
132 private final int[] runLen;
135 * Creates a TimSort instance to maintain the state of an ongoing sort.
137 * @param a the array to be sorted
138 * @param c the comparator to determine the order of the sort
140 private TimSort(T[] a, Comparator<? super T> c) {
144 // Allocate temp storage (which may be increased later if necessary)
146 @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
147 T[] newArray = (T[]) new Object[len < 2 * INITIAL_TMP_STORAGE_LENGTH ?
148 len >>> 1 : INITIAL_TMP_STORAGE_LENGTH];
152 * Allocate runs-to-be-merged stack (which cannot be expanded). The
153 * stack length requirements are described in listsort.txt. The C
154 * version always uses the same stack length (85), but this was
155 * measured to be too expensive when sorting "mid-sized" arrays (e.g.,
156 * 100 elements) in Java. Therefore, we use smaller (but sufficiently
157 * large) stack lengths for smaller arrays. The "magic numbers" in the
158 * computation below must be changed if MIN_MERGE is decreased. See
159 * the MIN_MERGE declaration above for more information.
161 int stackLen = (len < 120 ? 5 :
163 len < 119151 ? 19 : 40);
164 runBase = new int[stackLen];
165 runLen = new int[stackLen];
169 * The next two methods (which are package private and static) constitute
170 * the entire API of this class. Each of these methods obeys the contract
171 * of the public method with the same signature in java.util.Arrays.
174 static <T> void sort(T[] a, Comparator<? super T> c) {
175 sort(a, 0, a.length, c);
178 static <T> void sort(T[] a, int lo, int hi, Comparator<? super T> c) {
180 Arrays.sort(a, lo, hi);
184 rangeCheck(a.length, lo, hi);
185 int nRemaining = hi - lo;
187 return; // Arrays of size 0 and 1 are always sorted
189 // If array is small, do a "mini-TimSort" with no merges
190 if (nRemaining < MIN_MERGE) {
191 int initRunLen = countRunAndMakeAscending(a, lo, hi, c);
192 binarySort(a, lo, hi, lo + initRunLen, c);
197 * March over the array once, left to right, finding natural runs,
198 * extending short natural runs to minRun elements, and merging runs
199 * to maintain stack invariant.
201 TimSort<T> ts = new TimSort<>(a, c);
202 int minRun = minRunLength(nRemaining);
205 int runLen = countRunAndMakeAscending(a, lo, hi, c);
207 // If run is short, extend to min(minRun, nRemaining)
208 if (runLen < minRun) {
209 int force = nRemaining <= minRun ? nRemaining : minRun;
210 binarySort(a, lo, lo + force, lo + runLen, c);
214 // Push run onto pending-run stack, and maybe merge
215 ts.pushRun(lo, runLen);
218 // Advance to find next run
220 nRemaining -= runLen;
221 } while (nRemaining != 0);
223 // Merge all remaining runs to complete sort
225 ts.mergeForceCollapse();
226 assert ts.stackSize == 1;
230 * Sorts the specified portion of the specified array using a binary
231 * insertion sort. This is the best method for sorting small numbers
232 * of elements. It requires O(n log n) compares, but O(n^2) data
233 * movement (worst case).
235 * If the initial part of the specified range is already sorted,
236 * this method can take advantage of it: the method assumes that the
237 * elements from index {@code lo}, inclusive, to {@code start},
238 * exclusive are already sorted.
240 * @param a the array in which a range is to be sorted
241 * @param lo the index of the first element in the range to be sorted
242 * @param hi the index after the last element in the range to be sorted
243 * @param start the index of the first element in the range that is
244 * not already known to be sorted ({@code lo <= start <= hi})
245 * @param c comparator to used for the sort
247 @SuppressWarnings("fallthrough")
248 private static <T> void binarySort(T[] a, int lo, int hi, int start,
249 Comparator<? super T> c) {
250 assert lo <= start && start <= hi;
253 for ( ; start < hi; start++) {
256 // Set left (and right) to the index where a[start] (pivot) belongs
259 assert left <= right;
262 * pivot >= all in [lo, left).
263 * pivot < all in [right, start).
265 while (left < right) {
266 int mid = (left + right) >>> 1;
267 if (c.compare(pivot, a[mid]) < 0)
272 assert left == right;
275 * The invariants still hold: pivot >= all in [lo, left) and
276 * pivot < all in [left, start), so pivot belongs at left. Note
277 * that if there are elements equal to pivot, left points to the
278 * first slot after them -- that's why this sort is stable.
279 * Slide elements over to make room for pivot.
281 int n = start - left; // The number of elements to move
282 // Switch is just an optimization for arraycopy in default case
284 case 2: a[left + 2] = a[left + 1];
285 case 1: a[left + 1] = a[left];
287 default: System.arraycopy(a, left, a, left + 1, n);
294 * Returns the length of the run beginning at the specified position in
295 * the specified array and reverses the run if it is descending (ensuring
296 * that the run will always be ascending when the method returns).
298 * A run is the longest ascending sequence with:
300 * a[lo] <= a[lo + 1] <= a[lo + 2] <= ...
302 * or the longest descending sequence with:
304 * a[lo] > a[lo + 1] > a[lo + 2] > ...
306 * For its intended use in a stable mergesort, the strictness of the
307 * definition of "descending" is needed so that the call can safely
308 * reverse a descending sequence without violating stability.
310 * @param a the array in which a run is to be counted and possibly reversed
311 * @param lo index of the first element in the run
312 * @param hi index after the last element that may be contained in the run.
313 It is required that {@code lo < hi}.
314 * @param c the comparator to used for the sort
315 * @return the length of the run beginning at the specified position in
316 * the specified array
318 private static <T> int countRunAndMakeAscending(T[] a, int lo, int hi,
319 Comparator<? super T> c) {
325 // Find end of run, and reverse range if descending
326 if (c.compare(a[runHi++], a[lo]) < 0) { // Descending
327 while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0)
329 reverseRange(a, lo, runHi);
330 } else { // Ascending
331 while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0)
339 * Reverse the specified range of the specified array.
341 * @param a the array in which a range is to be reversed
342 * @param lo the index of the first element in the range to be reversed
343 * @param hi the index after the last element in the range to be reversed
345 private static void reverseRange(Object[] a, int lo, int hi) {
355 * Returns the minimum acceptable run length for an array of the specified
356 * length. Natural runs shorter than this will be extended with
357 * {@link #binarySort}.
359 * Roughly speaking, the computation is:
361 * If n < MIN_MERGE, return n (it's too small to bother with fancy stuff).
362 * Else if n is an exact power of 2, return MIN_MERGE/2.
363 * Else return an int k, MIN_MERGE/2 <= k <= MIN_MERGE, such that n/k
364 * is close to, but strictly less than, an exact power of 2.
366 * For the rationale, see listsort.txt.
368 * @param n the length of the array to be sorted
369 * @return the length of the minimum run to be merged
371 private static int minRunLength(int n) {
373 int r = 0; // Becomes 1 if any 1 bits are shifted off
374 while (n >= MIN_MERGE) {
382 * Pushes the specified run onto the pending-run stack.
384 * @param runBase index of the first element in the run
385 * @param runLen the number of elements in the run
387 private void pushRun(int runBase, int runLen) {
388 this.runBase[stackSize] = runBase;
389 this.runLen[stackSize] = runLen;
394 * Examines the stack of runs waiting to be merged and merges adjacent runs
395 * until the stack invariants are reestablished:
397 * 1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1]
398 * 2. runLen[i - 2] > runLen[i - 1]
400 * This method is called each time a new run is pushed onto the stack,
401 * so the invariants are guaranteed to hold for i < stackSize upon
402 * entry to the method.
404 private void mergeCollapse() {
405 while (stackSize > 1) {
406 int n = stackSize - 2;
407 if (n > 0 && runLen[n-1] <= runLen[n] + runLen[n+1]) {
408 if (runLen[n - 1] < runLen[n + 1])
411 } else if (runLen[n] <= runLen[n + 1]) {
414 break; // Invariant is established
420 * Merges all runs on the stack until only one remains. This method is
421 * called once, to complete the sort.
423 private void mergeForceCollapse() {
424 while (stackSize > 1) {
425 int n = stackSize - 2;
426 if (n > 0 && runLen[n - 1] < runLen[n + 1])
433 * Merges the two runs at stack indices i and i+1. Run i must be
434 * the penultimate or antepenultimate run on the stack. In other words,
435 * i must be equal to stackSize-2 or stackSize-3.
437 * @param i stack index of the first of the two runs to merge
439 private void mergeAt(int i) {
440 assert stackSize >= 2;
442 assert i == stackSize - 2 || i == stackSize - 3;
444 int base1 = runBase[i];
445 int len1 = runLen[i];
446 int base2 = runBase[i + 1];
447 int len2 = runLen[i + 1];
448 assert len1 > 0 && len2 > 0;
449 assert base1 + len1 == base2;
452 * Record the length of the combined runs; if i is the 3rd-last
453 * run now, also slide over the last run (which isn't involved
454 * in this merge). The current run (i+1) goes away in any case.
456 runLen[i] = len1 + len2;
457 if (i == stackSize - 3) {
458 runBase[i + 1] = runBase[i + 2];
459 runLen[i + 1] = runLen[i + 2];
464 * Find where the first element of run2 goes in run1. Prior elements
465 * in run1 can be ignored (because they're already in place).
467 int k = gallopRight(a[base2], a, base1, len1, 0, c);
475 * Find where the last element of run1 goes in run2. Subsequent elements
476 * in run2 can be ignored (because they're already in place).
478 len2 = gallopLeft(a[base1 + len1 - 1], a, base2, len2, len2 - 1, c);
483 // Merge remaining runs, using tmp array with min(len1, len2) elements
485 mergeLo(base1, len1, base2, len2);
487 mergeHi(base1, len1, base2, len2);
491 * Locates the position at which to insert the specified key into the
492 * specified sorted range; if the range contains an element equal to key,
493 * returns the index of the leftmost equal element.
495 * @param key the key whose insertion point to search for
496 * @param a the array in which to search
497 * @param base the index of the first element in the range
498 * @param len the length of the range; must be > 0
499 * @param hint the index at which to begin the search, 0 <= hint < n.
500 * The closer hint is to the result, the faster this method will run.
501 * @param c the comparator used to order the range, and to search
502 * @return the int k, 0 <= k <= n such that a[b + k - 1] < key <= a[b + k],
503 * pretending that a[b - 1] is minus infinity and a[b + n] is infinity.
504 * In other words, key belongs at index b + k; or in other words,
505 * the first k elements of a should precede key, and the last n - k
508 private static <T> int gallopLeft(T key, T[] a, int base, int len, int hint,
509 Comparator<? super T> c) {
510 assert len > 0 && hint >= 0 && hint < len;
513 if (c.compare(key, a[base + hint]) > 0) {
514 // Gallop right until a[base+hint+lastOfs] < key <= a[base+hint+ofs]
515 int maxOfs = len - hint;
516 while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) > 0) {
518 ofs = (ofs << 1) + 1;
519 if (ofs <= 0) // int overflow
525 // Make offsets relative to base
528 } else { // key <= a[base + hint]
529 // Gallop left until a[base+hint-ofs] < key <= a[base+hint-lastOfs]
530 final int maxOfs = hint + 1;
531 while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) <= 0) {
533 ofs = (ofs << 1) + 1;
534 if (ofs <= 0) // int overflow
540 // Make offsets relative to base
542 lastOfs = hint - ofs;
545 assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
548 * Now a[base+lastOfs] < key <= a[base+ofs], so key belongs somewhere
549 * to the right of lastOfs but no farther right than ofs. Do a binary
550 * search, with invariant a[base + lastOfs - 1] < key <= a[base + ofs].
553 while (lastOfs < ofs) {
554 int m = lastOfs + ((ofs - lastOfs) >>> 1);
556 if (c.compare(key, a[base + m]) > 0)
557 lastOfs = m + 1; // a[base + m] < key
559 ofs = m; // key <= a[base + m]
561 assert lastOfs == ofs; // so a[base + ofs - 1] < key <= a[base + ofs]
566 * Like gallopLeft, except that if the range contains an element equal to
567 * key, gallopRight returns the index after the rightmost equal element.
569 * @param key the key whose insertion point to search for
570 * @param a the array in which to search
571 * @param base the index of the first element in the range
572 * @param len the length of the range; must be > 0
573 * @param hint the index at which to begin the search, 0 <= hint < n.
574 * The closer hint is to the result, the faster this method will run.
575 * @param c the comparator used to order the range, and to search
576 * @return the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k]
578 private static <T> int gallopRight(T key, T[] a, int base, int len,
579 int hint, Comparator<? super T> c) {
580 assert len > 0 && hint >= 0 && hint < len;
584 if (c.compare(key, a[base + hint]) < 0) {
585 // Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs]
586 int maxOfs = hint + 1;
587 while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) < 0) {
589 ofs = (ofs << 1) + 1;
590 if (ofs <= 0) // int overflow
596 // Make offsets relative to b
598 lastOfs = hint - ofs;
600 } else { // a[b + hint] <= key
601 // Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs]
602 int maxOfs = len - hint;
603 while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) >= 0) {
605 ofs = (ofs << 1) + 1;
606 if (ofs <= 0) // int overflow
612 // Make offsets relative to b
616 assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
619 * Now a[b + lastOfs] <= key < a[b + ofs], so key belongs somewhere to
620 * the right of lastOfs but no farther right than ofs. Do a binary
621 * search, with invariant a[b + lastOfs - 1] <= key < a[b + ofs].
624 while (lastOfs < ofs) {
625 int m = lastOfs + ((ofs - lastOfs) >>> 1);
627 if (c.compare(key, a[base + m]) < 0)
628 ofs = m; // key < a[b + m]
630 lastOfs = m + 1; // a[b + m] <= key
632 assert lastOfs == ofs; // so a[b + ofs - 1] <= key < a[b + ofs]
637 * Merges two adjacent runs in place, in a stable fashion. The first
638 * element of the first run must be greater than the first element of the
639 * second run (a[base1] > a[base2]), and the last element of the first run
640 * (a[base1 + len1-1]) must be greater than all elements of the second run.
642 * For performance, this method should be called only when len1 <= len2;
643 * its twin, mergeHi should be called if len1 >= len2. (Either method
644 * may be called if len1 == len2.)
646 * @param base1 index of first element in first run to be merged
647 * @param len1 length of first run to be merged (must be > 0)
648 * @param base2 index of first element in second run to be merged
649 * (must be aBase + aLen)
650 * @param len2 length of second run to be merged (must be > 0)
652 private void mergeLo(int base1, int len1, int base2, int len2) {
653 assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
655 // Copy first run into temp array
656 T[] a = this.a; // For performance
657 T[] tmp = ensureCapacity(len1);
658 System.arraycopy(a, base1, tmp, 0, len1);
660 int cursor1 = 0; // Indexes into tmp array
661 int cursor2 = base2; // Indexes int a
662 int dest = base1; // Indexes int a
664 // Move first element of second run and deal with degenerate cases
665 a[dest++] = a[cursor2++];
667 System.arraycopy(tmp, cursor1, a, dest, len1);
671 System.arraycopy(a, cursor2, a, dest, len2);
672 a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge
676 Comparator<? super T> c = this.c; // Use local variable for performance
677 int minGallop = this.minGallop; // " " " " "
680 int count1 = 0; // Number of times in a row that first run won
681 int count2 = 0; // Number of times in a row that second run won
684 * Do the straightforward thing until (if ever) one run starts
685 * winning consistently.
688 assert len1 > 1 && len2 > 0;
689 if (c.compare(a[cursor2], tmp[cursor1]) < 0) {
690 a[dest++] = a[cursor2++];
696 a[dest++] = tmp[cursor1++];
702 } while ((count1 | count2) < minGallop);
705 * One run is winning so consistently that galloping may be a
706 * huge win. So try that, and continue galloping until (if ever)
707 * neither run appears to be winning consistently anymore.
710 assert len1 > 1 && len2 > 0;
711 count1 = gallopRight(a[cursor2], tmp, cursor1, len1, 0, c);
713 System.arraycopy(tmp, cursor1, a, dest, count1);
717 if (len1 <= 1) // len1 == 1 || len1 == 0
720 a[dest++] = a[cursor2++];
724 count2 = gallopLeft(tmp[cursor1], a, cursor2, len2, 0, c);
726 System.arraycopy(a, cursor2, a, dest, count2);
733 a[dest++] = tmp[cursor1++];
737 } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
740 minGallop += 2; // Penalize for leaving gallop mode
741 } // End of "outer" loop
742 this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field
746 System.arraycopy(a, cursor2, a, dest, len2);
747 a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge
748 } else if (len1 == 0) {
749 throw new IllegalArgumentException(
750 "Comparison method violates its general contract!");
754 System.arraycopy(tmp, cursor1, a, dest, len1);
759 * Like mergeLo, except that this method should be called only if
760 * len1 >= len2; mergeLo should be called if len1 <= len2. (Either method
761 * may be called if len1 == len2.)
763 * @param base1 index of first element in first run to be merged
764 * @param len1 length of first run to be merged (must be > 0)
765 * @param base2 index of first element in second run to be merged
766 * (must be aBase + aLen)
767 * @param len2 length of second run to be merged (must be > 0)
769 private void mergeHi(int base1, int len1, int base2, int len2) {
770 assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
772 // Copy second run into temp array
773 T[] a = this.a; // For performance
774 T[] tmp = ensureCapacity(len2);
775 System.arraycopy(a, base2, tmp, 0, len2);
777 int cursor1 = base1 + len1 - 1; // Indexes into a
778 int cursor2 = len2 - 1; // Indexes into tmp array
779 int dest = base2 + len2 - 1; // Indexes into a
781 // Move last element of first run and deal with degenerate cases
782 a[dest--] = a[cursor1--];
784 System.arraycopy(tmp, 0, a, dest - (len2 - 1), len2);
790 System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
791 a[dest] = tmp[cursor2];
795 Comparator<? super T> c = this.c; // Use local variable for performance
796 int minGallop = this.minGallop; // " " " " "
799 int count1 = 0; // Number of times in a row that first run won
800 int count2 = 0; // Number of times in a row that second run won
803 * Do the straightforward thing until (if ever) one run
804 * appears to win consistently.
807 assert len1 > 0 && len2 > 1;
808 if (c.compare(tmp[cursor2], a[cursor1]) < 0) {
809 a[dest--] = a[cursor1--];
815 a[dest--] = tmp[cursor2--];
821 } while ((count1 | count2) < minGallop);
824 * One run is winning so consistently that galloping may be a
825 * huge win. So try that, and continue galloping until (if ever)
826 * neither run appears to be winning consistently anymore.
829 assert len1 > 0 && len2 > 1;
830 count1 = len1 - gallopRight(tmp[cursor2], a, base1, len1, len1 - 1, c);
835 System.arraycopy(a, cursor1 + 1, a, dest + 1, count1);
839 a[dest--] = tmp[cursor2--];
843 count2 = len2 - gallopLeft(a[cursor1], tmp, 0, len2, len2 - 1, c);
848 System.arraycopy(tmp, cursor2 + 1, a, dest + 1, count2);
849 if (len2 <= 1) // len2 == 1 || len2 == 0
852 a[dest--] = a[cursor1--];
856 } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
859 minGallop += 2; // Penalize for leaving gallop mode
860 } // End of "outer" loop
861 this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field
867 System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
868 a[dest] = tmp[cursor2]; // Move first elt of run2 to front of merge
869 } else if (len2 == 0) {
870 throw new IllegalArgumentException(
871 "Comparison method violates its general contract!");
875 System.arraycopy(tmp, 0, a, dest - (len2 - 1), len2);
880 * Ensures that the external array tmp has at least the specified
881 * number of elements, increasing its size if necessary. The size
882 * increases exponentially to ensure amortized linear time complexity.
884 * @param minCapacity the minimum required capacity of the tmp array
885 * @return tmp, whether or not it grew
887 private T[] ensureCapacity(int minCapacity) {
888 if (tmp.length < minCapacity) {
889 // Compute smallest power of 2 > minCapacity
890 int newSize = minCapacity;
891 newSize |= newSize >> 1;
892 newSize |= newSize >> 2;
893 newSize |= newSize >> 4;
894 newSize |= newSize >> 8;
895 newSize |= newSize >> 16;
898 if (newSize < 0) // Not bloody likely!
899 newSize = minCapacity;
901 newSize = Math.min(newSize, a.length >>> 1);
903 @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
904 T[] newArray = (T[]) new Object[newSize];
911 * Checks that fromIndex and toIndex are in range, and throws an
912 * appropriate exception if they aren't.
914 * @param arrayLen the length of the array
915 * @param fromIndex the index of the first element of the range
916 * @param toIndex the index after the last element of the range
917 * @throws IllegalArgumentException if fromIndex > toIndex
918 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
919 * or toIndex > arrayLen
921 private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
922 if (fromIndex > toIndex)
923 throw new IllegalArgumentException("fromIndex(" + fromIndex +
924 ") > toIndex(" + toIndex+")");
926 throw new ArrayIndexOutOfBoundsException(fromIndex);
927 if (toIndex > arrayLen)
928 throw new ArrayIndexOutOfBoundsException(toIndex);