TimSort.java revision 02f409d949c9d50806809b827ec503765bed34fd
1/*
2 * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
3 * Copyright 2009 Google Inc.  All Rights Reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.  Oracle designates this
9 * particular file as subject to the "Classpath" exception as provided
10 * by Oracle in the LICENSE file that accompanied this code.
11 *
12 * This code is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 * version 2 for more details (a copy is included in the LICENSE file that
16 * accompanied this code).
17 *
18 * You should have received a copy of the GNU General Public License version
19 * 2 along with this work; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23 * or visit www.oracle.com if you need additional information or have any
24 * questions.
25 */
26
27package java.util;
28
29/**
30 * A stable, adaptive, iterative mergesort that requires far fewer than
31 * n lg(n) comparisons when running on partially sorted arrays, while
32 * offering performance comparable to a traditional mergesort when run
33 * on random arrays.  Like all proper mergesorts, this sort is stable and
34 * runs O(n log n) time (worst case).  In the worst case, this sort requires
35 * temporary storage space for n/2 object references; in the best case,
36 * it requires only a small constant amount of space.
37 *
38 * This implementation was adapted from Tim Peters's list sort for
39 * Python, which is described in detail here:
40 *
41 *   http://svn.python.org/projects/python/trunk/Objects/listsort.txt
42 *
43 * Tim's C code may be found here:
44 *
45 *   http://svn.python.org/projects/python/trunk/Objects/listobject.c
46 *
47 * The underlying techniques are described in this paper (and may have
48 * even earlier origins):
49 *
50 *  "Optimistic Sorting and Information Theoretic Complexity"
51 *  Peter McIlroy
52 *  SODA (Fourth Annual ACM-SIAM Symposium on Discrete Algorithms),
53 *  pp 467-474, Austin, Texas, 25-27 January 1993.
54 *
55 * While the API to this class consists solely of static methods, it is
56 * (privately) instantiable; a TimSort instance holds the state of an ongoing
57 * sort, assuming the input array is large enough to warrant the full-blown
58 * TimSort. Small arrays are sorted in place, using a binary insertion sort.
59 *
60 * @author Josh Bloch
61 */
62class TimSort<T> {
63    /**
64     * This is the minimum sized sequence that will be merged.  Shorter
65     * sequences will be lengthened by calling binarySort.  If the entire
66     * array is less than this length, no merges will be performed.
67     *
68     * This constant should be a power of two.  It was 64 in Tim Peter's C
69     * implementation, but 32 was empirically determined to work better in
70     * this implementation.  In the unlikely event that you set this constant
71     * to be a number that's not a power of two, you'll need to change the
72     * {@link #minRunLength} computation.
73     *
74     * If you decrease this constant, you must change the stackLen
75     * computation in the TimSort constructor, or you risk an
76     * ArrayOutOfBounds exception.  See listsort.txt for a discussion
77     * of the minimum stack length required as a function of the length
78     * of the array being sorted and the minimum merge sequence length.
79     */
80    private static final int MIN_MERGE = 32;
81
82    /**
83     * The array being sorted.
84     */
85    private final T[] a;
86
87    /**
88     * The comparator for this sort.
89     */
90    private final Comparator<? super T> c;
91
92    /**
93     * When we get into galloping mode, we stay there until both runs win less
94     * often than MIN_GALLOP consecutive times.
95     */
96    private static final int  MIN_GALLOP = 7;
97
98    /**
99     * This controls when we get *into* galloping mode.  It is initialized
100     * to MIN_GALLOP.  The mergeLo and mergeHi methods nudge it higher for
101     * random data, and lower for highly structured data.
102     */
103    private int minGallop = MIN_GALLOP;
104
105    /**
106     * Maximum initial size of tmp array, which is used for merging.  The array
107     * can grow to accommodate demand.
108     *
109     * Unlike Tim's original C version, we do not allocate this much storage
110     * when sorting smaller arrays.  This change was required for performance.
111     */
112    private static final int INITIAL_TMP_STORAGE_LENGTH = 256;
113
114    /**
115     * Temp storage for merges.
116     */
117    private T[] tmp; // Actual runtime type will be Object[], regardless of T
118
119    /**
120     * A stack of pending runs yet to be merged.  Run i starts at
121     * address base[i] and extends for len[i] elements.  It's always
122     * true (so long as the indices are in bounds) that:
123     *
124     *     runBase[i] + runLen[i] == runBase[i + 1]
125     *
126     * so we could cut the storage for this, but it's a minor amount,
127     * and keeping all the info explicit simplifies the code.
128     */
129    private int stackSize = 0;  // Number of pending runs on stack
130    private final int[] runBase;
131    private final int[] runLen;
132
133    /**
134     * Creates a TimSort instance to maintain the state of an ongoing sort.
135     *
136     * @param a the array to be sorted
137     * @param c the comparator to determine the order of the sort
138     */
139    private TimSort(T[] a, Comparator<? super T> c) {
140        this.a = a;
141        this.c = c;
142
143        // Allocate temp storage (which may be increased later if necessary)
144        int len = a.length;
145        @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
146        T[] newArray = (T[]) new Object[len < 2 * INITIAL_TMP_STORAGE_LENGTH ?
147                                        len >>> 1 : INITIAL_TMP_STORAGE_LENGTH];
148        tmp = newArray;
149
150        /*
151         * Allocate runs-to-be-merged stack (which cannot be expanded).  The
152         * stack length requirements are described in listsort.txt.  The C
153         * version always uses the same stack length (85), but this was
154         * measured to be too expensive when sorting "mid-sized" arrays (e.g.,
155         * 100 elements) in Java.  Therefore, we use smaller (but sufficiently
156         * large) stack lengths for smaller arrays.  The "magic numbers" in the
157         * computation below must be changed if MIN_MERGE is decreased.  See
158         * the MIN_MERGE declaration above for more information.
159         */
160        int stackLen = (len <    120  ?  5 :
161                        len <   1542  ? 10 :
162                        len < 119151  ? 24 : 40);
163        runBase = new int[stackLen];
164        runLen = new int[stackLen];
165    }
166
167    /*
168     * The next two methods (which are package private and static) constitute
169     * the entire API of this class.  Each of these methods obeys the contract
170     * of the public method with the same signature in java.util.Arrays.
171     */
172
173    static <T> void sort(T[] a, Comparator<? super T> c) {
174        sort(a, 0, a.length, c);
175    }
176
177    static <T> void sort(T[] a, int lo, int hi, Comparator<? super T> c) {
178        if (c == null) {
179            Arrays.sort(a, lo, hi);
180            return;
181        }
182
183        rangeCheck(a.length, lo, hi);
184        int nRemaining  = hi - lo;
185        if (nRemaining < 2)
186            return;  // Arrays of size 0 and 1 are always sorted
187
188        // If array is small, do a "mini-TimSort" with no merges
189        if (nRemaining < MIN_MERGE) {
190            int initRunLen = countRunAndMakeAscending(a, lo, hi, c);
191            binarySort(a, lo, hi, lo + initRunLen, c);
192            return;
193        }
194
195        /**
196         * March over the array once, left to right, finding natural runs,
197         * extending short natural runs to minRun elements, and merging runs
198         * to maintain stack invariant.
199         */
200        TimSort<T> ts = new TimSort<>(a, c);
201        int minRun = minRunLength(nRemaining);
202        do {
203            // Identify next run
204            int runLen = countRunAndMakeAscending(a, lo, hi, c);
205
206            // If run is short, extend to min(minRun, nRemaining)
207            if (runLen < minRun) {
208                int force = nRemaining <= minRun ? nRemaining : minRun;
209                binarySort(a, lo, lo + force, lo + runLen, c);
210                runLen = force;
211            }
212
213            // Push run onto pending-run stack, and maybe merge
214            ts.pushRun(lo, runLen);
215            ts.mergeCollapse();
216
217            // Advance to find next run
218            lo += runLen;
219            nRemaining -= runLen;
220        } while (nRemaining != 0);
221
222        // Merge all remaining runs to complete sort
223        assert lo == hi;
224        ts.mergeForceCollapse();
225        assert ts.stackSize == 1;
226    }
227
228    /**
229     * Sorts the specified portion of the specified array using a binary
230     * insertion sort.  This is the best method for sorting small numbers
231     * of elements.  It requires O(n log n) compares, but O(n^2) data
232     * movement (worst case).
233     *
234     * If the initial part of the specified range is already sorted,
235     * this method can take advantage of it: the method assumes that the
236     * elements from index {@code lo}, inclusive, to {@code start},
237     * exclusive are already sorted.
238     *
239     * @param a the array in which a range is to be sorted
240     * @param lo the index of the first element in the range to be sorted
241     * @param hi the index after the last element in the range to be sorted
242     * @param start the index of the first element in the range that is
243     *        not already known to be sorted ({@code lo <= start <= hi})
244     * @param c comparator to used for the sort
245     */
246    @SuppressWarnings("fallthrough")
247    private static <T> void binarySort(T[] a, int lo, int hi, int start,
248                                       Comparator<? super T> c) {
249        assert lo <= start && start <= hi;
250        if (start == lo)
251            start++;
252        for ( ; start < hi; start++) {
253            T pivot = a[start];
254
255            // Set left (and right) to the index where a[start] (pivot) belongs
256            int left = lo;
257            int right = start;
258            assert left <= right;
259            /*
260             * Invariants:
261             *   pivot >= all in [lo, left).
262             *   pivot <  all in [right, start).
263             */
264            while (left < right) {
265                int mid = (left + right) >>> 1;
266                if (c.compare(pivot, a[mid]) < 0)
267                    right = mid;
268                else
269                    left = mid + 1;
270            }
271            assert left == right;
272
273            /*
274             * The invariants still hold: pivot >= all in [lo, left) and
275             * pivot < all in [left, start), so pivot belongs at left.  Note
276             * that if there are elements equal to pivot, left points to the
277             * first slot after them -- that's why this sort is stable.
278             * Slide elements over to make room for pivot.
279             */
280            int n = start - left;  // The number of elements to move
281            // Switch is just an optimization for arraycopy in default case
282            switch (n) {
283                case 2:  a[left + 2] = a[left + 1];
284                case 1:  a[left + 1] = a[left];
285                         break;
286                default: System.arraycopy(a, left, a, left + 1, n);
287            }
288            a[left] = pivot;
289        }
290    }
291
292    /**
293     * Returns the length of the run beginning at the specified position in
294     * the specified array and reverses the run if it is descending (ensuring
295     * that the run will always be ascending when the method returns).
296     *
297     * A run is the longest ascending sequence with:
298     *
299     *    a[lo] <= a[lo + 1] <= a[lo + 2] <= ...
300     *
301     * or the longest descending sequence with:
302     *
303     *    a[lo] >  a[lo + 1] >  a[lo + 2] >  ...
304     *
305     * For its intended use in a stable mergesort, the strictness of the
306     * definition of "descending" is needed so that the call can safely
307     * reverse a descending sequence without violating stability.
308     *
309     * @param a the array in which a run is to be counted and possibly reversed
310     * @param lo index of the first element in the run
311     * @param hi index after the last element that may be contained in the run.
312              It is required that {@code lo < hi}.
313     * @param c the comparator to used for the sort
314     * @return  the length of the run beginning at the specified position in
315     *          the specified array
316     */
317    private static <T> int countRunAndMakeAscending(T[] a, int lo, int hi,
318                                                    Comparator<? super T> c) {
319        assert lo < hi;
320        int runHi = lo + 1;
321        if (runHi == hi)
322            return 1;
323
324        // Find end of run, and reverse range if descending
325        if (c.compare(a[runHi++], a[lo]) < 0) { // Descending
326            while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0)
327                runHi++;
328            reverseRange(a, lo, runHi);
329        } else {                              // Ascending
330            while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0)
331                runHi++;
332        }
333
334        return runHi - lo;
335    }
336
337    /**
338     * Reverse the specified range of the specified array.
339     *
340     * @param a the array in which a range is to be reversed
341     * @param lo the index of the first element in the range to be reversed
342     * @param hi the index after the last element in the range to be reversed
343     */
344    private static void reverseRange(Object[] a, int lo, int hi) {
345        hi--;
346        while (lo < hi) {
347            Object t = a[lo];
348            a[lo++] = a[hi];
349            a[hi--] = t;
350        }
351    }
352
353    /**
354     * Returns the minimum acceptable run length for an array of the specified
355     * length. Natural runs shorter than this will be extended with
356     * {@link #binarySort}.
357     *
358     * Roughly speaking, the computation is:
359     *
360     *  If n < MIN_MERGE, return n (it's too small to bother with fancy stuff).
361     *  Else if n is an exact power of 2, return MIN_MERGE/2.
362     *  Else return an int k, MIN_MERGE/2 <= k <= MIN_MERGE, such that n/k
363     *   is close to, but strictly less than, an exact power of 2.
364     *
365     * For the rationale, see listsort.txt.
366     *
367     * @param n the length of the array to be sorted
368     * @return the length of the minimum run to be merged
369     */
370    private static int minRunLength(int n) {
371        assert n >= 0;
372        int r = 0;      // Becomes 1 if any 1 bits are shifted off
373        while (n >= MIN_MERGE) {
374            r |= (n & 1);
375            n >>= 1;
376        }
377        return n + r;
378    }
379
380    /**
381     * Pushes the specified run onto the pending-run stack.
382     *
383     * @param runBase index of the first element in the run
384     * @param runLen  the number of elements in the run
385     */
386    private void pushRun(int runBase, int runLen) {
387        this.runBase[stackSize] = runBase;
388        this.runLen[stackSize] = runLen;
389        stackSize++;
390    }
391
392    /**
393     * Examines the stack of runs waiting to be merged and merges adjacent runs
394     * until the stack invariants are reestablished:
395     *
396     *     1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1]
397     *     2. runLen[i - 2] > runLen[i - 1]
398     *
399     * This method is called each time a new run is pushed onto the stack,
400     * so the invariants are guaranteed to hold for i < stackSize upon
401     * entry to the method.
402     */
403    private void mergeCollapse() {
404        while (stackSize > 1) {
405            int n = stackSize - 2;
406            if (n > 0 && runLen[n-1] <= runLen[n] + runLen[n+1]) {
407                if (runLen[n - 1] < runLen[n + 1])
408                    n--;
409                mergeAt(n);
410            } else if (runLen[n] <= runLen[n + 1]) {
411                mergeAt(n);
412            } else {
413                break; // Invariant is established
414            }
415        }
416    }
417
418    /**
419     * Merges all runs on the stack until only one remains.  This method is
420     * called once, to complete the sort.
421     */
422    private void mergeForceCollapse() {
423        while (stackSize > 1) {
424            int n = stackSize - 2;
425            if (n > 0 && runLen[n - 1] < runLen[n + 1])
426                n--;
427            mergeAt(n);
428        }
429    }
430
431    /**
432     * Merges the two runs at stack indices i and i+1.  Run i must be
433     * the penultimate or antepenultimate run on the stack.  In other words,
434     * i must be equal to stackSize-2 or stackSize-3.
435     *
436     * @param i stack index of the first of the two runs to merge
437     */
438    private void mergeAt(int i) {
439        assert stackSize >= 2;
440        assert i >= 0;
441        assert i == stackSize - 2 || i == stackSize - 3;
442
443        int base1 = runBase[i];
444        int len1 = runLen[i];
445        int base2 = runBase[i + 1];
446        int len2 = runLen[i + 1];
447        assert len1 > 0 && len2 > 0;
448        assert base1 + len1 == base2;
449
450        /*
451         * Record the length of the combined runs; if i is the 3rd-last
452         * run now, also slide over the last run (which isn't involved
453         * in this merge).  The current run (i+1) goes away in any case.
454         */
455        runLen[i] = len1 + len2;
456        if (i == stackSize - 3) {
457            runBase[i + 1] = runBase[i + 2];
458            runLen[i + 1] = runLen[i + 2];
459        }
460        stackSize--;
461
462        /*
463         * Find where the first element of run2 goes in run1. Prior elements
464         * in run1 can be ignored (because they're already in place).
465         */
466        int k = gallopRight(a[base2], a, base1, len1, 0, c);
467        assert k >= 0;
468        base1 += k;
469        len1 -= k;
470        if (len1 == 0)
471            return;
472
473        /*
474         * Find where the last element of run1 goes in run2. Subsequent elements
475         * in run2 can be ignored (because they're already in place).
476         */
477        len2 = gallopLeft(a[base1 + len1 - 1], a, base2, len2, len2 - 1, c);
478        assert len2 >= 0;
479        if (len2 == 0)
480            return;
481
482        // Merge remaining runs, using tmp array with min(len1, len2) elements
483        if (len1 <= len2)
484            mergeLo(base1, len1, base2, len2);
485        else
486            mergeHi(base1, len1, base2, len2);
487    }
488
489    /**
490     * Locates the position at which to insert the specified key into the
491     * specified sorted range; if the range contains an element equal to key,
492     * returns the index of the leftmost equal element.
493     *
494     * @param key the key whose insertion point to search for
495     * @param a the array in which to search
496     * @param base the index of the first element in the range
497     * @param len the length of the range; must be > 0
498     * @param hint the index at which to begin the search, 0 <= hint < n.
499     *     The closer hint is to the result, the faster this method will run.
500     * @param c the comparator used to order the range, and to search
501     * @return the int k,  0 <= k <= n such that a[b + k - 1] < key <= a[b + k],
502     *    pretending that a[b - 1] is minus infinity and a[b + n] is infinity.
503     *    In other words, key belongs at index b + k; or in other words,
504     *    the first k elements of a should precede key, and the last n - k
505     *    should follow it.
506     */
507    private static <T> int gallopLeft(T key, T[] a, int base, int len, int hint,
508                                      Comparator<? super T> c) {
509        assert len > 0 && hint >= 0 && hint < len;
510        int lastOfs = 0;
511        int ofs = 1;
512        if (c.compare(key, a[base + hint]) > 0) {
513            // Gallop right until a[base+hint+lastOfs] < key <= a[base+hint+ofs]
514            int maxOfs = len - hint;
515            while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) > 0) {
516                lastOfs = ofs;
517                ofs = (ofs << 1) + 1;
518                if (ofs <= 0)   // int overflow
519                    ofs = maxOfs;
520            }
521            if (ofs > maxOfs)
522                ofs = maxOfs;
523
524            // Make offsets relative to base
525            lastOfs += hint;
526            ofs += hint;
527        } else { // key <= a[base + hint]
528            // Gallop left until a[base+hint-ofs] < key <= a[base+hint-lastOfs]
529            final int maxOfs = hint + 1;
530            while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) <= 0) {
531                lastOfs = ofs;
532                ofs = (ofs << 1) + 1;
533                if (ofs <= 0)   // int overflow
534                    ofs = maxOfs;
535            }
536            if (ofs > maxOfs)
537                ofs = maxOfs;
538
539            // Make offsets relative to base
540            int tmp = lastOfs;
541            lastOfs = hint - ofs;
542            ofs = hint - tmp;
543        }
544        assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
545
546        /*
547         * Now a[base+lastOfs] < key <= a[base+ofs], so key belongs somewhere
548         * to the right of lastOfs but no farther right than ofs.  Do a binary
549         * search, with invariant a[base + lastOfs - 1] < key <= a[base + ofs].
550         */
551        lastOfs++;
552        while (lastOfs < ofs) {
553            int m = lastOfs + ((ofs - lastOfs) >>> 1);
554
555            if (c.compare(key, a[base + m]) > 0)
556                lastOfs = m + 1;  // a[base + m] < key
557            else
558                ofs = m;          // key <= a[base + m]
559        }
560        assert lastOfs == ofs;    // so a[base + ofs - 1] < key <= a[base + ofs]
561        return ofs;
562    }
563
564    /**
565     * Like gallopLeft, except that if the range contains an element equal to
566     * key, gallopRight returns the index after the rightmost equal element.
567     *
568     * @param key the key whose insertion point to search for
569     * @param a the array in which to search
570     * @param base the index of the first element in the range
571     * @param len the length of the range; must be > 0
572     * @param hint the index at which to begin the search, 0 <= hint < n.
573     *     The closer hint is to the result, the faster this method will run.
574     * @param c the comparator used to order the range, and to search
575     * @return the int k,  0 <= k <= n such that a[b + k - 1] <= key < a[b + k]
576     */
577    private static <T> int gallopRight(T key, T[] a, int base, int len,
578                                       int hint, Comparator<? super T> c) {
579        assert len > 0 && hint >= 0 && hint < len;
580
581        int ofs = 1;
582        int lastOfs = 0;
583        if (c.compare(key, a[base + hint]) < 0) {
584            // Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs]
585            int maxOfs = hint + 1;
586            while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) < 0) {
587                lastOfs = ofs;
588                ofs = (ofs << 1) + 1;
589                if (ofs <= 0)   // int overflow
590                    ofs = maxOfs;
591            }
592            if (ofs > maxOfs)
593                ofs = maxOfs;
594
595            // Make offsets relative to b
596            int tmp = lastOfs;
597            lastOfs = hint - ofs;
598            ofs = hint - tmp;
599        } else { // a[b + hint] <= key
600            // Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs]
601            int maxOfs = len - hint;
602            while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) >= 0) {
603                lastOfs = ofs;
604                ofs = (ofs << 1) + 1;
605                if (ofs <= 0)   // int overflow
606                    ofs = maxOfs;
607            }
608            if (ofs > maxOfs)
609                ofs = maxOfs;
610
611            // Make offsets relative to b
612            lastOfs += hint;
613            ofs += hint;
614        }
615        assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
616
617        /*
618         * Now a[b + lastOfs] <= key < a[b + ofs], so key belongs somewhere to
619         * the right of lastOfs but no farther right than ofs.  Do a binary
620         * search, with invariant a[b + lastOfs - 1] <= key < a[b + ofs].
621         */
622        lastOfs++;
623        while (lastOfs < ofs) {
624            int m = lastOfs + ((ofs - lastOfs) >>> 1);
625
626            if (c.compare(key, a[base + m]) < 0)
627                ofs = m;          // key < a[b + m]
628            else
629                lastOfs = m + 1;  // a[b + m] <= key
630        }
631        assert lastOfs == ofs;    // so a[b + ofs - 1] <= key < a[b + ofs]
632        return ofs;
633    }
634
635    /**
636     * Merges two adjacent runs in place, in a stable fashion.  The first
637     * element of the first run must be greater than the first element of the
638     * second run (a[base1] > a[base2]), and the last element of the first run
639     * (a[base1 + len1-1]) must be greater than all elements of the second run.
640     *
641     * For performance, this method should be called only when len1 <= len2;
642     * its twin, mergeHi should be called if len1 >= len2.  (Either method
643     * may be called if len1 == len2.)
644     *
645     * @param base1 index of first element in first run to be merged
646     * @param len1  length of first run to be merged (must be > 0)
647     * @param base2 index of first element in second run to be merged
648     *        (must be aBase + aLen)
649     * @param len2  length of second run to be merged (must be > 0)
650     */
651    private void mergeLo(int base1, int len1, int base2, int len2) {
652        assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
653
654        // Copy first run into temp array
655        T[] a = this.a; // For performance
656        T[] tmp = ensureCapacity(len1);
657        System.arraycopy(a, base1, tmp, 0, len1);
658
659        int cursor1 = 0;       // Indexes into tmp array
660        int cursor2 = base2;   // Indexes int a
661        int dest = base1;      // Indexes int a
662
663        // Move first element of second run and deal with degenerate cases
664        a[dest++] = a[cursor2++];
665        if (--len2 == 0) {
666            System.arraycopy(tmp, cursor1, a, dest, len1);
667            return;
668        }
669        if (len1 == 1) {
670            System.arraycopy(a, cursor2, a, dest, len2);
671            a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge
672            return;
673        }
674
675        Comparator<? super T> c = this.c;  // Use local variable for performance
676        int minGallop = this.minGallop;    //  "    "       "     "      "
677    outer:
678        while (true) {
679            int count1 = 0; // Number of times in a row that first run won
680            int count2 = 0; // Number of times in a row that second run won
681
682            /*
683             * Do the straightforward thing until (if ever) one run starts
684             * winning consistently.
685             */
686            do {
687                assert len1 > 1 && len2 > 0;
688                if (c.compare(a[cursor2], tmp[cursor1]) < 0) {
689                    a[dest++] = a[cursor2++];
690                    count2++;
691                    count1 = 0;
692                    if (--len2 == 0)
693                        break outer;
694                } else {
695                    a[dest++] = tmp[cursor1++];
696                    count1++;
697                    count2 = 0;
698                    if (--len1 == 1)
699                        break outer;
700                }
701            } while ((count1 | count2) < minGallop);
702
703            /*
704             * One run is winning so consistently that galloping may be a
705             * huge win. So try that, and continue galloping until (if ever)
706             * neither run appears to be winning consistently anymore.
707             */
708            do {
709                assert len1 > 1 && len2 > 0;
710                count1 = gallopRight(a[cursor2], tmp, cursor1, len1, 0, c);
711                if (count1 != 0) {
712                    System.arraycopy(tmp, cursor1, a, dest, count1);
713                    dest += count1;
714                    cursor1 += count1;
715                    len1 -= count1;
716                    if (len1 <= 1) // len1 == 1 || len1 == 0
717                        break outer;
718                }
719                a[dest++] = a[cursor2++];
720                if (--len2 == 0)
721                    break outer;
722
723                count2 = gallopLeft(tmp[cursor1], a, cursor2, len2, 0, c);
724                if (count2 != 0) {
725                    System.arraycopy(a, cursor2, a, dest, count2);
726                    dest += count2;
727                    cursor2 += count2;
728                    len2 -= count2;
729                    if (len2 == 0)
730                        break outer;
731                }
732                a[dest++] = tmp[cursor1++];
733                if (--len1 == 1)
734                    break outer;
735                minGallop--;
736            } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
737            if (minGallop < 0)
738                minGallop = 0;
739            minGallop += 2;  // Penalize for leaving gallop mode
740        }  // End of "outer" loop
741        this.minGallop = minGallop < 1 ? 1 : minGallop;  // Write back to field
742
743        if (len1 == 1) {
744            assert len2 > 0;
745            System.arraycopy(a, cursor2, a, dest, len2);
746            a[dest + len2] = tmp[cursor1]; //  Last elt of run 1 to end of merge
747        } else if (len1 == 0) {
748            throw new IllegalArgumentException(
749                "Comparison method violates its general contract!");
750        } else {
751            assert len2 == 0;
752            assert len1 > 1;
753            System.arraycopy(tmp, cursor1, a, dest, len1);
754        }
755    }
756
757    /**
758     * Like mergeLo, except that this method should be called only if
759     * len1 >= len2; mergeLo should be called if len1 <= len2.  (Either method
760     * may be called if len1 == len2.)
761     *
762     * @param base1 index of first element in first run to be merged
763     * @param len1  length of first run to be merged (must be > 0)
764     * @param base2 index of first element in second run to be merged
765     *        (must be aBase + aLen)
766     * @param len2  length of second run to be merged (must be > 0)
767     */
768    private void mergeHi(int base1, int len1, int base2, int len2) {
769        assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
770
771        // Copy second run into temp array
772        T[] a = this.a; // For performance
773        T[] tmp = ensureCapacity(len2);
774        System.arraycopy(a, base2, tmp, 0, len2);
775
776        int cursor1 = base1 + len1 - 1;  // Indexes into a
777        int cursor2 = len2 - 1;          // Indexes into tmp array
778        int dest = base2 + len2 - 1;     // Indexes into a
779
780        // Move last element of first run and deal with degenerate cases
781        a[dest--] = a[cursor1--];
782        if (--len1 == 0) {
783            System.arraycopy(tmp, 0, a, dest - (len2 - 1), len2);
784            return;
785        }
786        if (len2 == 1) {
787            dest -= len1;
788            cursor1 -= len1;
789            System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
790            a[dest] = tmp[cursor2];
791            return;
792        }
793
794        Comparator<? super T> c = this.c;  // Use local variable for performance
795        int minGallop = this.minGallop;    //  "    "       "     "      "
796    outer:
797        while (true) {
798            int count1 = 0; // Number of times in a row that first run won
799            int count2 = 0; // Number of times in a row that second run won
800
801            /*
802             * Do the straightforward thing until (if ever) one run
803             * appears to win consistently.
804             */
805            do {
806                assert len1 > 0 && len2 > 1;
807                if (c.compare(tmp[cursor2], a[cursor1]) < 0) {
808                    a[dest--] = a[cursor1--];
809                    count1++;
810                    count2 = 0;
811                    if (--len1 == 0)
812                        break outer;
813                } else {
814                    a[dest--] = tmp[cursor2--];
815                    count2++;
816                    count1 = 0;
817                    if (--len2 == 1)
818                        break outer;
819                }
820            } while ((count1 | count2) < minGallop);
821
822            /*
823             * One run is winning so consistently that galloping may be a
824             * huge win. So try that, and continue galloping until (if ever)
825             * neither run appears to be winning consistently anymore.
826             */
827            do {
828                assert len1 > 0 && len2 > 1;
829                count1 = len1 - gallopRight(tmp[cursor2], a, base1, len1, len1 - 1, c);
830                if (count1 != 0) {
831                    dest -= count1;
832                    cursor1 -= count1;
833                    len1 -= count1;
834                    System.arraycopy(a, cursor1 + 1, a, dest + 1, count1);
835                    if (len1 == 0)
836                        break outer;
837                }
838                a[dest--] = tmp[cursor2--];
839                if (--len2 == 1)
840                    break outer;
841
842                count2 = len2 - gallopLeft(a[cursor1], tmp, 0, len2, len2 - 1, c);
843                if (count2 != 0) {
844                    dest -= count2;
845                    cursor2 -= count2;
846                    len2 -= count2;
847                    System.arraycopy(tmp, cursor2 + 1, a, dest + 1, count2);
848                    if (len2 <= 1)  // len2 == 1 || len2 == 0
849                        break outer;
850                }
851                a[dest--] = a[cursor1--];
852                if (--len1 == 0)
853                    break outer;
854                minGallop--;
855            } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
856            if (minGallop < 0)
857                minGallop = 0;
858            minGallop += 2;  // Penalize for leaving gallop mode
859        }  // End of "outer" loop
860        this.minGallop = minGallop < 1 ? 1 : minGallop;  // Write back to field
861
862        if (len2 == 1) {
863            assert len1 > 0;
864            dest -= len1;
865            cursor1 -= len1;
866            System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
867            a[dest] = tmp[cursor2];  // Move first elt of run2 to front of merge
868        } else if (len2 == 0) {
869            throw new IllegalArgumentException(
870                "Comparison method violates its general contract!");
871        } else {
872            assert len1 == 0;
873            assert len2 > 0;
874            System.arraycopy(tmp, 0, a, dest - (len2 - 1), len2);
875        }
876    }
877
878    /**
879     * Ensures that the external array tmp has at least the specified
880     * number of elements, increasing its size if necessary.  The size
881     * increases exponentially to ensure amortized linear time complexity.
882     *
883     * @param minCapacity the minimum required capacity of the tmp array
884     * @return tmp, whether or not it grew
885     */
886    private T[] ensureCapacity(int minCapacity) {
887        if (tmp.length < minCapacity) {
888            // Compute smallest power of 2 > minCapacity
889            int newSize = minCapacity;
890            newSize |= newSize >> 1;
891            newSize |= newSize >> 2;
892            newSize |= newSize >> 4;
893            newSize |= newSize >> 8;
894            newSize |= newSize >> 16;
895            newSize++;
896
897            if (newSize < 0) // Not bloody likely!
898                newSize = minCapacity;
899            else
900                newSize = Math.min(newSize, a.length >>> 1);
901
902            @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
903            T[] newArray = (T[]) new Object[newSize];
904            tmp = newArray;
905        }
906        return tmp;
907    }
908
909    /**
910     * Checks that fromIndex and toIndex are in range, and throws an
911     * appropriate exception if they aren't.
912     *
913     * @param arrayLen the length of the array
914     * @param fromIndex the index of the first element of the range
915     * @param toIndex the index after the last element of the range
916     * @throws IllegalArgumentException if fromIndex > toIndex
917     * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
918     *         or toIndex > arrayLen
919     */
920    private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
921        if (fromIndex > toIndex)
922            throw new IllegalArgumentException("fromIndex(" + fromIndex +
923                       ") > toIndex(" + toIndex+")");
924        if (fromIndex < 0)
925            throw new ArrayIndexOutOfBoundsException(fromIndex);
926        if (toIndex > arrayLen)
927            throw new ArrayIndexOutOfBoundsException(toIndex);
928    }
929}
930