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 * This is a near duplicate of {@link TimSort}, modified for use with
32 * arrays of objects that implement {@link Comparable}, instead of using
33 * explicit comparators.
35 * <p>If you are using an optimizing VM, you may find that ComparableTimSort
36 * offers no performance benefit over TimSort in conjunction with a
37 * comparator that simply returns {@code ((Comparable)first).compareTo(Second)}.
38 * If this is the case, you are better off deleting ComparableTimSort to
39 * eliminate the code duplication. (See Arrays.java for details.)
43 class ComparableTimSort {
45 * This is the minimum sized sequence that will be merged. Shorter
46 * sequences will be lengthened by calling binarySort. If the entire
47 * array is less than this length, no merges will be performed.
49 * This constant should be a power of two. It was 64 in Tim Peter's C
50 * implementation, but 32 was empirically determined to work better in
51 * this implementation. In the unlikely event that you set this constant
52 * to be a number that's not a power of two, you'll need to change the
53 * {@link #minRunLength} computation.
55 * If you decrease this constant, you must change the stackLen
56 * computation in the TimSort constructor, or you risk an
57 * ArrayOutOfBounds exception. See listsort.txt for a discussion
58 * of the minimum stack length required as a function of the length
59 * of the array being sorted and the minimum merge sequence length.
61 private static final int MIN_MERGE = 32;
64 * The array being sorted.
66 private final Object[] a;
69 * When we get into galloping mode, we stay there until both runs win less
70 * often than MIN_GALLOP consecutive times.
72 private static final int MIN_GALLOP = 7;
75 * This controls when we get *into* galloping mode. It is initialized
76 * to MIN_GALLOP. The mergeLo and mergeHi methods nudge it higher for
77 * random data, and lower for highly structured data.
79 private int minGallop = MIN_GALLOP;
82 * Maximum initial size of tmp array, which is used for merging. The array
83 * can grow to accommodate demand.
85 * Unlike Tim's original C version, we do not allocate this much storage
86 * when sorting smaller arrays. This change was required for performance.
88 private static final int INITIAL_TMP_STORAGE_LENGTH = 256;
91 * Temp storage for merges.
96 * A stack of pending runs yet to be merged. Run i starts at
97 * address base[i] and extends for len[i] elements. It's always
98 * true (so long as the indices are in bounds) that:
100 * runBase[i] + runLen[i] == runBase[i + 1]
102 * so we could cut the storage for this, but it's a minor amount,
103 * and keeping all the info explicit simplifies the code.
105 private int stackSize = 0; // Number of pending runs on stack
106 private final int[] runBase;
107 private final int[] runLen;
110 * Creates a TimSort instance to maintain the state of an ongoing sort.
112 * @param a the array to be sorted
114 private ComparableTimSort(Object[] a) {
117 // Allocate temp storage (which may be increased later if necessary)
119 @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
120 Object[] newArray = new Object[len < 2 * INITIAL_TMP_STORAGE_LENGTH ?
121 len >>> 1 : INITIAL_TMP_STORAGE_LENGTH];
125 * Allocate runs-to-be-merged stack (which cannot be expanded). The
126 * stack length requirements are described in listsort.txt. The C
127 * version always uses the same stack length (85), but this was
128 * measured to be too expensive when sorting "mid-sized" arrays (e.g.,
129 * 100 elements) in Java. Therefore, we use smaller (but sufficiently
130 * large) stack lengths for smaller arrays. The "magic numbers" in the
131 * computation below must be changed if MIN_MERGE is decreased. See
132 * the MIN_MERGE declaration above for more information.
134 int stackLen = (len < 120 ? 5 :
136 len < 119151 ? 19 : 40);
137 runBase = new int[stackLen];
138 runLen = new int[stackLen];
142 * The next two methods (which are package private and static) constitute
143 * the entire API of this class. Each of these methods obeys the contract
144 * of the public method with the same signature in java.util.Arrays.
147 static void sort(Object[] a) {
148 sort(a, 0, a.length);
151 static void sort(Object[] a, int lo, int hi) {
152 rangeCheck(a.length, lo, hi);
153 int nRemaining = hi - lo;
155 return; // Arrays of size 0 and 1 are always sorted
157 // If array is small, do a "mini-TimSort" with no merges
158 if (nRemaining < MIN_MERGE) {
159 int initRunLen = countRunAndMakeAscending(a, lo, hi);
160 binarySort(a, lo, hi, lo + initRunLen);
165 * March over the array once, left to right, finding natural runs,
166 * extending short natural runs to minRun elements, and merging runs
167 * to maintain stack invariant.
169 ComparableTimSort ts = new ComparableTimSort(a);
170 int minRun = minRunLength(nRemaining);
173 int runLen = countRunAndMakeAscending(a, lo, hi);
175 // If run is short, extend to min(minRun, nRemaining)
176 if (runLen < minRun) {
177 int force = nRemaining <= minRun ? nRemaining : minRun;
178 binarySort(a, lo, lo + force, lo + runLen);
182 // Push run onto pending-run stack, and maybe merge
183 ts.pushRun(lo, runLen);
186 // Advance to find next run
188 nRemaining -= runLen;
189 } while (nRemaining != 0);
191 // Merge all remaining runs to complete sort
193 ts.mergeForceCollapse();
194 assert ts.stackSize == 1;
198 * Sorts the specified portion of the specified array using a binary
199 * insertion sort. This is the best method for sorting small numbers
200 * of elements. It requires O(n log n) compares, but O(n^2) data
201 * movement (worst case).
203 * If the initial part of the specified range is already sorted,
204 * this method can take advantage of it: the method assumes that the
205 * elements from index {@code lo}, inclusive, to {@code start},
206 * exclusive are already sorted.
208 * @param a the array in which a range is to be sorted
209 * @param lo the index of the first element in the range to be sorted
210 * @param hi the index after the last element in the range to be sorted
211 * @param start the index of the first element in the range that is
212 * not already known to be sorted ({@code lo <= start <= hi})
214 @SuppressWarnings("fallthrough")
215 private static void binarySort(Object[] a, int lo, int hi, int start) {
216 assert lo <= start && start <= hi;
219 for ( ; start < hi; start++) {
220 @SuppressWarnings("unchecked")
221 Comparable<Object> pivot = (Comparable) a[start];
223 // Set left (and right) to the index where a[start] (pivot) belongs
226 assert left <= right;
229 * pivot >= all in [lo, left).
230 * pivot < all in [right, start).
232 while (left < right) {
233 int mid = (left + right) >>> 1;
234 if (pivot.compareTo(a[mid]) < 0)
239 assert left == right;
242 * The invariants still hold: pivot >= all in [lo, left) and
243 * pivot < all in [left, start), so pivot belongs at left. Note
244 * that if there are elements equal to pivot, left points to the
245 * first slot after them -- that's why this sort is stable.
246 * Slide elements over to make room for pivot.
248 int n = start - left; // The number of elements to move
249 // Switch is just an optimization for arraycopy in default case
251 case 2: a[left + 2] = a[left + 1];
252 case 1: a[left + 1] = a[left];
254 default: System.arraycopy(a, left, a, left + 1, n);
261 * Returns the length of the run beginning at the specified position in
262 * the specified array and reverses the run if it is descending (ensuring
263 * that the run will always be ascending when the method returns).
265 * A run is the longest ascending sequence with:
267 * a[lo] <= a[lo + 1] <= a[lo + 2] <= ...
269 * or the longest descending sequence with:
271 * a[lo] > a[lo + 1] > a[lo + 2] > ...
273 * For its intended use in a stable mergesort, the strictness of the
274 * definition of "descending" is needed so that the call can safely
275 * reverse a descending sequence without violating stability.
277 * @param a the array in which a run is to be counted and possibly reversed
278 * @param lo index of the first element in the run
279 * @param hi index after the last element that may be contained in the run.
280 It is required that {@code lo < hi}.
281 * @return the length of the run beginning at the specified position in
282 * the specified array
284 @SuppressWarnings("unchecked")
285 private static int countRunAndMakeAscending(Object[] a, int lo, int hi) {
291 // Find end of run, and reverse range if descending
292 if (((Comparable) a[runHi++]).compareTo(a[lo]) < 0) { // Descending
293 while (runHi < hi && ((Comparable) a[runHi]).compareTo(a[runHi - 1]) < 0)
295 reverseRange(a, lo, runHi);
296 } else { // Ascending
297 while (runHi < hi && ((Comparable) a[runHi]).compareTo(a[runHi - 1]) >= 0)
305 * Reverse the specified range of the specified array.
307 * @param a the array in which a range is to be reversed
308 * @param lo the index of the first element in the range to be reversed
309 * @param hi the index after the last element in the range to be reversed
311 private static void reverseRange(Object[] a, int lo, int hi) {
321 * Returns the minimum acceptable run length for an array of the specified
322 * length. Natural runs shorter than this will be extended with
323 * {@link #binarySort}.
325 * Roughly speaking, the computation is:
327 * If n < MIN_MERGE, return n (it's too small to bother with fancy stuff).
328 * Else if n is an exact power of 2, return MIN_MERGE/2.
329 * Else return an int k, MIN_MERGE/2 <= k <= MIN_MERGE, such that n/k
330 * is close to, but strictly less than, an exact power of 2.
332 * For the rationale, see listsort.txt.
334 * @param n the length of the array to be sorted
335 * @return the length of the minimum run to be merged
337 private static int minRunLength(int n) {
339 int r = 0; // Becomes 1 if any 1 bits are shifted off
340 while (n >= MIN_MERGE) {
348 * Pushes the specified run onto the pending-run stack.
350 * @param runBase index of the first element in the run
351 * @param runLen the number of elements in the run
353 private void pushRun(int runBase, int runLen) {
354 this.runBase[stackSize] = runBase;
355 this.runLen[stackSize] = runLen;
360 * Examines the stack of runs waiting to be merged and merges adjacent runs
361 * until the stack invariants are reestablished:
363 * 1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1]
364 * 2. runLen[i - 2] > runLen[i - 1]
366 * This method is called each time a new run is pushed onto the stack,
367 * so the invariants are guaranteed to hold for i < stackSize upon
368 * entry to the method.
370 private void mergeCollapse() {
371 while (stackSize > 1) {
372 int n = stackSize - 2;
373 if (n > 0 && runLen[n-1] <= runLen[n] + runLen[n+1]) {
374 if (runLen[n - 1] < runLen[n + 1])
377 } else if (runLen[n] <= runLen[n + 1]) {
380 break; // Invariant is established
386 * Merges all runs on the stack until only one remains. This method is
387 * called once, to complete the sort.
389 private void mergeForceCollapse() {
390 while (stackSize > 1) {
391 int n = stackSize - 2;
392 if (n > 0 && runLen[n - 1] < runLen[n + 1])
399 * Merges the two runs at stack indices i and i+1. Run i must be
400 * the penultimate or antepenultimate run on the stack. In other words,
401 * i must be equal to stackSize-2 or stackSize-3.
403 * @param i stack index of the first of the two runs to merge
405 @SuppressWarnings("unchecked")
406 private void mergeAt(int i) {
407 assert stackSize >= 2;
409 assert i == stackSize - 2 || i == stackSize - 3;
411 int base1 = runBase[i];
412 int len1 = runLen[i];
413 int base2 = runBase[i + 1];
414 int len2 = runLen[i + 1];
415 assert len1 > 0 && len2 > 0;
416 assert base1 + len1 == base2;
419 * Record the length of the combined runs; if i is the 3rd-last
420 * run now, also slide over the last run (which isn't involved
421 * in this merge). The current run (i+1) goes away in any case.
423 runLen[i] = len1 + len2;
424 if (i == stackSize - 3) {
425 runBase[i + 1] = runBase[i + 2];
426 runLen[i + 1] = runLen[i + 2];
431 * Find where the first element of run2 goes in run1. Prior elements
432 * in run1 can be ignored (because they're already in place).
434 int k = gallopRight((Comparable<Object>) a[base2], a, base1, len1, 0);
442 * Find where the last element of run1 goes in run2. Subsequent elements
443 * in run2 can be ignored (because they're already in place).
445 len2 = gallopLeft((Comparable<Object>) a[base1 + len1 - 1], a,
446 base2, len2, len2 - 1);
451 // Merge remaining runs, using tmp array with min(len1, len2) elements
453 mergeLo(base1, len1, base2, len2);
455 mergeHi(base1, len1, base2, len2);
459 * Locates the position at which to insert the specified key into the
460 * specified sorted range; if the range contains an element equal to key,
461 * returns the index of the leftmost equal element.
463 * @param key the key whose insertion point to search for
464 * @param a the array in which to search
465 * @param base the index of the first element in the range
466 * @param len the length of the range; must be > 0
467 * @param hint the index at which to begin the search, 0 <= hint < n.
468 * The closer hint is to the result, the faster this method will run.
469 * @return the int k, 0 <= k <= n such that a[b + k - 1] < key <= a[b + k],
470 * pretending that a[b - 1] is minus infinity and a[b + n] is infinity.
471 * In other words, key belongs at index b + k; or in other words,
472 * the first k elements of a should precede key, and the last n - k
475 private static int gallopLeft(Comparable<Object> key, Object[] a,
476 int base, int len, int hint) {
477 assert len > 0 && hint >= 0 && hint < len;
481 if (key.compareTo(a[base + hint]) > 0) {
482 // Gallop right until a[base+hint+lastOfs] < key <= a[base+hint+ofs]
483 int maxOfs = len - hint;
484 while (ofs < maxOfs && key.compareTo(a[base + hint + ofs]) > 0) {
486 ofs = (ofs << 1) + 1;
487 if (ofs <= 0) // int overflow
493 // Make offsets relative to base
496 } else { // key <= a[base + hint]
497 // Gallop left until a[base+hint-ofs] < key <= a[base+hint-lastOfs]
498 final int maxOfs = hint + 1;
499 while (ofs < maxOfs && key.compareTo(a[base + hint - ofs]) <= 0) {
501 ofs = (ofs << 1) + 1;
502 if (ofs <= 0) // int overflow
508 // Make offsets relative to base
510 lastOfs = hint - ofs;
513 assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
516 * Now a[base+lastOfs] < key <= a[base+ofs], so key belongs somewhere
517 * to the right of lastOfs but no farther right than ofs. Do a binary
518 * search, with invariant a[base + lastOfs - 1] < key <= a[base + ofs].
521 while (lastOfs < ofs) {
522 int m = lastOfs + ((ofs - lastOfs) >>> 1);
524 if (key.compareTo(a[base + m]) > 0)
525 lastOfs = m + 1; // a[base + m] < key
527 ofs = m; // key <= a[base + m]
529 assert lastOfs == ofs; // so a[base + ofs - 1] < key <= a[base + ofs]
534 * Like gallopLeft, except that if the range contains an element equal to
535 * key, gallopRight returns the index after the rightmost equal element.
537 * @param key the key whose insertion point to search for
538 * @param a the array in which to search
539 * @param base the index of the first element in the range
540 * @param len the length of the range; must be > 0
541 * @param hint the index at which to begin the search, 0 <= hint < n.
542 * The closer hint is to the result, the faster this method will run.
543 * @return the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k]
545 private static int gallopRight(Comparable<Object> key, Object[] a,
546 int base, int len, int hint) {
547 assert len > 0 && hint >= 0 && hint < len;
551 if (key.compareTo(a[base + hint]) < 0) {
552 // Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs]
553 int maxOfs = hint + 1;
554 while (ofs < maxOfs && key.compareTo(a[base + hint - ofs]) < 0) {
556 ofs = (ofs << 1) + 1;
557 if (ofs <= 0) // int overflow
563 // Make offsets relative to b
565 lastOfs = hint - ofs;
567 } else { // a[b + hint] <= key
568 // Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs]
569 int maxOfs = len - hint;
570 while (ofs < maxOfs && key.compareTo(a[base + hint + ofs]) >= 0) {
572 ofs = (ofs << 1) + 1;
573 if (ofs <= 0) // int overflow
579 // Make offsets relative to b
583 assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
586 * Now a[b + lastOfs] <= key < a[b + ofs], so key belongs somewhere to
587 * the right of lastOfs but no farther right than ofs. Do a binary
588 * search, with invariant a[b + lastOfs - 1] <= key < a[b + ofs].
591 while (lastOfs < ofs) {
592 int m = lastOfs + ((ofs - lastOfs) >>> 1);
594 if (key.compareTo(a[base + m]) < 0)
595 ofs = m; // key < a[b + m]
597 lastOfs = m + 1; // a[b + m] <= key
599 assert lastOfs == ofs; // so a[b + ofs - 1] <= key < a[b + ofs]
604 * Merges two adjacent runs in place, in a stable fashion. The first
605 * element of the first run must be greater than the first element of the
606 * second run (a[base1] > a[base2]), and the last element of the first run
607 * (a[base1 + len1-1]) must be greater than all elements of the second run.
609 * For performance, this method should be called only when len1 <= len2;
610 * its twin, mergeHi should be called if len1 >= len2. (Either method
611 * may be called if len1 == len2.)
613 * @param base1 index of first element in first run to be merged
614 * @param len1 length of first run to be merged (must be > 0)
615 * @param base2 index of first element in second run to be merged
616 * (must be aBase + aLen)
617 * @param len2 length of second run to be merged (must be > 0)
619 @SuppressWarnings("unchecked")
620 private void mergeLo(int base1, int len1, int base2, int len2) {
621 assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
623 // Copy first run into temp array
624 Object[] a = this.a; // For performance
625 Object[] tmp = ensureCapacity(len1);
626 System.arraycopy(a, base1, tmp, 0, len1);
628 int cursor1 = 0; // Indexes into tmp array
629 int cursor2 = base2; // Indexes int a
630 int dest = base1; // Indexes int a
632 // Move first element of second run and deal with degenerate cases
633 a[dest++] = a[cursor2++];
635 System.arraycopy(tmp, cursor1, a, dest, len1);
639 System.arraycopy(a, cursor2, a, dest, len2);
640 a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge
644 int minGallop = this.minGallop; // Use local variable for performance
647 int count1 = 0; // Number of times in a row that first run won
648 int count2 = 0; // Number of times in a row that second run won
651 * Do the straightforward thing until (if ever) one run starts
652 * winning consistently.
655 assert len1 > 1 && len2 > 0;
656 if (((Comparable) a[cursor2]).compareTo(tmp[cursor1]) < 0) {
657 a[dest++] = a[cursor2++];
663 a[dest++] = tmp[cursor1++];
669 } while ((count1 | count2) < minGallop);
672 * One run is winning so consistently that galloping may be a
673 * huge win. So try that, and continue galloping until (if ever)
674 * neither run appears to be winning consistently anymore.
677 assert len1 > 1 && len2 > 0;
678 count1 = gallopRight((Comparable) a[cursor2], tmp, cursor1, len1, 0);
680 System.arraycopy(tmp, cursor1, a, dest, count1);
684 if (len1 <= 1) // len1 == 1 || len1 == 0
687 a[dest++] = a[cursor2++];
691 count2 = gallopLeft((Comparable) tmp[cursor1], a, cursor2, len2, 0);
693 System.arraycopy(a, cursor2, a, dest, count2);
700 a[dest++] = tmp[cursor1++];
704 } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
707 minGallop += 2; // Penalize for leaving gallop mode
708 } // End of "outer" loop
709 this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field
713 System.arraycopy(a, cursor2, a, dest, len2);
714 a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge
715 } else if (len1 == 0) {
716 throw new IllegalArgumentException(
717 "Comparison method violates its general contract!");
721 System.arraycopy(tmp, cursor1, a, dest, len1);
726 * Like mergeLo, except that this method should be called only if
727 * len1 >= len2; mergeLo should be called if len1 <= len2. (Either method
728 * may be called if len1 == len2.)
730 * @param base1 index of first element in first run to be merged
731 * @param len1 length of first run to be merged (must be > 0)
732 * @param base2 index of first element in second run to be merged
733 * (must be aBase + aLen)
734 * @param len2 length of second run to be merged (must be > 0)
736 @SuppressWarnings("unchecked")
737 private void mergeHi(int base1, int len1, int base2, int len2) {
738 assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
740 // Copy second run into temp array
741 Object[] a = this.a; // For performance
742 Object[] tmp = ensureCapacity(len2);
743 System.arraycopy(a, base2, tmp, 0, len2);
745 int cursor1 = base1 + len1 - 1; // Indexes into a
746 int cursor2 = len2 - 1; // Indexes into tmp array
747 int dest = base2 + len2 - 1; // Indexes into a
749 // Move last element of first run and deal with degenerate cases
750 a[dest--] = a[cursor1--];
752 System.arraycopy(tmp, 0, a, dest - (len2 - 1), len2);
758 System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
759 a[dest] = tmp[cursor2];
763 int minGallop = this.minGallop; // Use local variable for performance
766 int count1 = 0; // Number of times in a row that first run won
767 int count2 = 0; // Number of times in a row that second run won
770 * Do the straightforward thing until (if ever) one run
771 * appears to win consistently.
774 assert len1 > 0 && len2 > 1;
775 if (((Comparable) tmp[cursor2]).compareTo(a[cursor1]) < 0) {
776 a[dest--] = a[cursor1--];
782 a[dest--] = tmp[cursor2--];
788 } while ((count1 | count2) < minGallop);
791 * One run is winning so consistently that galloping may be a
792 * huge win. So try that, and continue galloping until (if ever)
793 * neither run appears to be winning consistently anymore.
796 assert len1 > 0 && len2 > 1;
797 count1 = len1 - gallopRight((Comparable) tmp[cursor2], a, base1, len1, len1 - 1);
802 System.arraycopy(a, cursor1 + 1, a, dest + 1, count1);
806 a[dest--] = tmp[cursor2--];
810 count2 = len2 - gallopLeft((Comparable) a[cursor1], tmp, 0, len2, len2 - 1);
815 System.arraycopy(tmp, cursor2 + 1, a, dest + 1, count2);
817 break outer; // len2 == 1 || len2 == 0
819 a[dest--] = a[cursor1--];
823 } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
826 minGallop += 2; // Penalize for leaving gallop mode
827 } // End of "outer" loop
828 this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field
834 System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
835 a[dest] = tmp[cursor2]; // Move first elt of run2 to front of merge
836 } else if (len2 == 0) {
837 throw new IllegalArgumentException(
838 "Comparison method violates its general contract!");
842 System.arraycopy(tmp, 0, a, dest - (len2 - 1), len2);
847 * Ensures that the external array tmp has at least the specified
848 * number of elements, increasing its size if necessary. The size
849 * increases exponentially to ensure amortized linear time complexity.
851 * @param minCapacity the minimum required capacity of the tmp array
852 * @return tmp, whether or not it grew
854 private Object[] ensureCapacity(int minCapacity) {
855 if (tmp.length < minCapacity) {
856 // Compute smallest power of 2 > minCapacity
857 int newSize = minCapacity;
858 newSize |= newSize >> 1;
859 newSize |= newSize >> 2;
860 newSize |= newSize >> 4;
861 newSize |= newSize >> 8;
862 newSize |= newSize >> 16;
865 if (newSize < 0) // Not bloody likely!
866 newSize = minCapacity;
868 newSize = Math.min(newSize, a.length >>> 1);
870 @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
871 Object[] newArray = new Object[newSize];
878 * Checks that fromIndex and toIndex are in range, and throws an
879 * appropriate exception if they aren't.
881 * @param arrayLen the length of the array
882 * @param fromIndex the index of the first element of the range
883 * @param toIndex the index after the last element of the range
884 * @throws IllegalArgumentException if fromIndex > toIndex
885 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
886 * or toIndex > arrayLen
888 private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
889 if (fromIndex > toIndex)
890 throw new IllegalArgumentException("fromIndex(" + fromIndex +
891 ") > toIndex(" + toIndex+")");
893 throw new ArrayIndexOutOfBoundsException(fromIndex);
894 if (toIndex > arrayLen)
895 throw new ArrayIndexOutOfBoundsException(toIndex);