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