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