DualPivotQuicksort.java 73.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/*
 * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package java.util;

/**
 * This class implements the Dual-Pivot Quicksort algorithm by
 * Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. The algorithm
 * offers O(n log(n)) performance on many data sets that cause other
 * quicksorts to degrade to quadratic performance, and is typically
 * faster than traditional (one-pivot) Quicksort implementations.
 *
 * @author Vladimir Yaroslavskiy
 * @author Jon Bentley
 * @author Josh Bloch
 *
A
alanb 已提交
39
 * @version 2009.11.09 m765.827.v8
40 41 42
 */
final class DualPivotQuicksort {

A
alanb 已提交
43
    // Suppresses default constructor
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    private DualPivotQuicksort() {}

    /*
     * Tuning Parameters.
     */

    /**
     * If the length of an array to be sorted is less than this
     * constant, insertion sort is used in preference to Quicksort.
     */
    private static final int INSERTION_SORT_THRESHOLD = 32;

    /**
     * If the length of a byte array to be sorted is greater than
     * this constant, counting sort is used in preference to Quicksort.
     */
    private static final int COUNTING_SORT_THRESHOLD_FOR_BYTE = 128;

    /**
     * If the length of a short or char array to be sorted is greater
     * than this constant, counting sort is used in preference to Quicksort.
     */
    private static final int COUNTING_SORT_THRESHOLD_FOR_SHORT_OR_CHAR = 32768;

    /*
     * Sorting methods for the seven primitive types.
     */

    /**
A
alanb 已提交
73
     * Sorts the specified array into ascending numerical order.
74 75 76
     *
     * @param a the array to be sorted
     */
A
alanb 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
    public static void sort(int[] a) {
        doSort(a, 0, a.length - 1);
    }

    /**
     * Sorts the specified range of the array into ascending order. The range
     * to be sorted extends from the index {@code fromIndex}, inclusive, to
     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
     * the range to be sorted is empty.
     *
     * @param a the array to be sorted
     * @param fromIndex the index of the first element, inclusive, to be sorted
     * @param toIndex the index of the last element, exclusive, to be sorted
     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
     * @throws ArrayIndexOutOfBoundsException
     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
     */
    public static void sort(int[] a, int fromIndex, int toIndex) {
        rangeCheck(a.length, fromIndex, toIndex);
        doSort(a, fromIndex, toIndex - 1);
    }

    /**
     * Sorts the specified range of the array into ascending order. This
     * method differs from the public {@code sort} method in that the
     * {@code right} index is inclusive, and it does no range checking on
     * {@code left} or {@code right}.
     *
     * @param a the array to be sorted
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
     */
    private static void doSort(int[] a, int left, int right) {
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
        // Use insertion sort on tiny arrays
        if (right - left + 1 < INSERTION_SORT_THRESHOLD) {
            for (int k = left + 1; k <= right; k++) {
                int ak = a[k];
                int j;

                for (j = k - 1; j >= left && ak < a[j]; j--) {
                    a[j + 1] = a[j];
                }
                a[j + 1] = ak;
            }
        } else { // Use Dual-Pivot Quicksort on large arrays
            dualPivotQuicksort(a, left, right);
        }
    }

    /**
A
alanb 已提交
127 128
     * Sorts the specified range of the array into ascending order by the
     * Dual-Pivot Quicksort algorithm.
129 130
     *
     * @param a the array to be sorted
A
alanb 已提交
131 132
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
     */
    private static void dualPivotQuicksort(int[] a, int left, int right) {
        // Compute indices of five evenly spaced elements
        int sixth = (right - left + 1) / 6;
        int e1 = left  + sixth;
        int e5 = right - sixth;
        int e3 = (left + right) >>> 1; // The midpoint
        int e4 = e3 + sixth;
        int e2 = e3 - sixth;

        // Sort these elements in place using a 5-element sorting network
        if (a[e1] > a[e2]) { int t = a[e1]; a[e1] = a[e2]; a[e2] = t; }
        if (a[e4] > a[e5]) { int t = a[e4]; a[e4] = a[e5]; a[e5] = t; }
        if (a[e1] > a[e3]) { int t = a[e1]; a[e1] = a[e3]; a[e3] = t; }
        if (a[e2] > a[e3]) { int t = a[e2]; a[e2] = a[e3]; a[e3] = t; }
        if (a[e1] > a[e4]) { int t = a[e1]; a[e1] = a[e4]; a[e4] = t; }
        if (a[e3] > a[e4]) { int t = a[e3]; a[e3] = a[e4]; a[e4] = t; }
        if (a[e2] > a[e5]) { int t = a[e2]; a[e2] = a[e5]; a[e5] = t; }
        if (a[e2] > a[e3]) { int t = a[e2]; a[e2] = a[e3]; a[e3] = t; }
        if (a[e4] > a[e5]) { int t = a[e4]; a[e4] = a[e5]; a[e5] = t; }

        /*
         * Use the second and fourth of the five sorted elements as pivots.
         * These values are inexpensive approximations of the first and
         * second terciles of the array. Note that pivot1 <= pivot2.
         *
         * The pivots are stored in local variables, and the first and
         * the last of the sorted elements are moved to the locations
         * formerly occupied by the pivots. When partitioning is complete,
         * the pivots are swapped back into their final positions, and
         * excluded from subsequent sorting.
         */
        int pivot1 = a[e2]; a[e2] = a[left];
        int pivot2 = a[e4]; a[e4] = a[right];

        /*
         * Partitioning
         *
         *   left part         center part                  right part
         * ------------------------------------------------------------
         * [ < pivot1  |  pivot1 <= && <= pivot2  |   ?   |  > pivot2 ]
         * ------------------------------------------------------------
         *              ^                          ^     ^
         *              |                          |     |
         *             less                        k   great
         */

        // Pointers
        int less  = left  + 1; // The index of first element of center part
        int great = right - 1; // The index before first element of right part

        boolean pivotsDiffer = pivot1 != pivot2;

        if (pivotsDiffer) {
            /*
             * Invariants:
             *              all in (left, less)   < pivot1
             *    pivot1 <= all in [less, k)     <= pivot2
             *              all in (great, right) > pivot2
             *
             * Pointer k is the first index of ?-part
             */
            for (int k = less; k <= great; k++) {
                int ak = a[k];

                if (ak < pivot1) {
                    a[k] = a[less];
                    a[less++] = ak;
                } else if (ak > pivot2) {
                    while (a[great] > pivot2 && k < great) {
                        great--;
                    }
                    a[k] = a[great];
                    a[great--] = ak;
                    ak = a[k];

                    if (ak < pivot1) {
                        a[k] = a[less];
                        a[less++] = ak;
                    }
                }
            }
        } else { // Pivots are equal
            /*
             * Partition degenerates to the traditional 3-way
             * (or "Dutch National Flag") partition:
             *
             *   left part   center part            right part
             * -------------------------------------------------
             * [  < pivot  |  == pivot  |    ?    |  > pivot   ]
             * -------------------------------------------------
             *
             *              ^            ^       ^
             *              |            |       |
             *             less          k     great
             *
             * Invariants:
             *
             *   all in (left, less)   < pivot
             *   all in [less, k)     == pivot
             *   all in (great, right) > pivot
             *
             * Pointer k is the first index of ?-part
             */
            for (int k = less; k <= great; k++) {
                int ak = a[k];

                if (ak == pivot1) {
                  continue;
                }
                if (ak < pivot1) {
                    a[k] = a[less];
                    a[less++] = ak;
                } else {
                    while (a[great] > pivot1) {
                        great--;
                    }
                    a[k] = a[great];
                    a[great--] = ak;
                    ak = a[k];

                    if (ak < pivot1) {
                        a[k] = a[less];
                        a[less++] = ak;
                    }
                }
            }
        }

        // Swap pivots into their final positions
        a[left]  = a[less  - 1]; a[less  - 1] = pivot1;
        a[right] = a[great + 1]; a[great + 1] = pivot2;

        // Sort left and right parts recursively, excluding known pivot values
A
alanb 已提交
267 268
        doSort(a, left,   less - 2);
        doSort(a, great + 2, right);
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303

        /*
         * If pivot1 == pivot2, all elements from center
         * part are equal and, therefore, already sorted
         */
        if (!pivotsDiffer) {
            return;
        }

        /*
         * If center part is too large (comprises > 5/6 of
         * the array), swap internal pivot values to ends
         */
        if (less < e1 && e5 < great) {
            while (a[less] == pivot1) {
                less++;
            }
            for (int k = less + 1; k <= great; k++) {
                if (a[k] == pivot1) {
                    a[k] = a[less];
                    a[less++] = pivot1;
                }
            }
            while (a[great] == pivot2) {
                great--;
            }
            for (int k = great - 1; k >= less; k--) {
                if (a[k] == pivot2) {
                    a[k] = a[great];
                    a[great--] = pivot2;
                }
            }
        }

        // Sort center part recursively, excluding known pivot values
A
alanb 已提交
304 305 306 307 308 309 310 311 312 313
        doSort(a, less, great);
    }

    /**
     * Sorts the specified array into ascending numerical order.
     *
     * @param a the array to be sorted
     */
    public static void sort(long[] a) {
        doSort(a, 0, a.length - 1);
314 315 316
    }

    /**
A
alanb 已提交
317 318 319 320
     * Sorts the specified range of the array into ascending order. The range
     * to be sorted extends from the index {@code fromIndex}, inclusive, to
     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
     * the range to be sorted is empty.
321 322
     *
     * @param a the array to be sorted
A
alanb 已提交
323 324 325 326 327
     * @param fromIndex the index of the first element, inclusive, to be sorted
     * @param toIndex the index of the last element, exclusive, to be sorted
     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
     * @throws ArrayIndexOutOfBoundsException
     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
328
     */
A
alanb 已提交
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    public static void sort(long[] a, int fromIndex, int toIndex) {
        rangeCheck(a.length, fromIndex, toIndex);
        doSort(a, fromIndex, toIndex - 1);
    }

    /**
     * Sorts the specified range of the array into ascending order. This
     * method differs from the public {@code sort} method in that the
     * {@code right} index is inclusive, and it does no range checking on
     * {@code left} or {@code right}.
     *
     * @param a the array to be sorted
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
     */
    private static void doSort(long[] a, int left, int right) {
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
        // Use insertion sort on tiny arrays
        if (right - left + 1 < INSERTION_SORT_THRESHOLD) {
            for (int k = left + 1; k <= right; k++) {
                long ak = a[k];
                int j;

                for (j = k - 1; j >= left && ak < a[j]; j--) {
                    a[j + 1] = a[j];
                }
                a[j + 1] = ak;
            }
        } else { // Use Dual-Pivot Quicksort on large arrays
            dualPivotQuicksort(a, left, right);
        }
    }

    /**
A
alanb 已提交
362 363
     * Sorts the specified range of the array into ascending order by the
     * Dual-Pivot Quicksort algorithm.
364 365
     *
     * @param a the array to be sorted
A
alanb 已提交
366 367
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
     */
    private static void dualPivotQuicksort(long[] a, int left, int right) {
        // Compute indices of five evenly spaced elements
        int sixth = (right - left + 1) / 6;
        int e1 = left  + sixth;
        int e5 = right - sixth;
        int e3 = (left + right) >>> 1; // The midpoint
        int e4 = e3 + sixth;
        int e2 = e3 - sixth;

        // Sort these elements in place using a 5-element sorting network
        if (a[e1] > a[e2]) { long t = a[e1]; a[e1] = a[e2]; a[e2] = t; }
        if (a[e4] > a[e5]) { long t = a[e4]; a[e4] = a[e5]; a[e5] = t; }
        if (a[e1] > a[e3]) { long t = a[e1]; a[e1] = a[e3]; a[e3] = t; }
        if (a[e2] > a[e3]) { long t = a[e2]; a[e2] = a[e3]; a[e3] = t; }
        if (a[e1] > a[e4]) { long t = a[e1]; a[e1] = a[e4]; a[e4] = t; }
        if (a[e3] > a[e4]) { long t = a[e3]; a[e3] = a[e4]; a[e4] = t; }
        if (a[e2] > a[e5]) { long t = a[e2]; a[e2] = a[e5]; a[e5] = t; }
        if (a[e2] > a[e3]) { long t = a[e2]; a[e2] = a[e3]; a[e3] = t; }
        if (a[e4] > a[e5]) { long t = a[e4]; a[e4] = a[e5]; a[e5] = t; }

        /*
         * Use the second and fourth of the five sorted elements as pivots.
         * These values are inexpensive approximations of the first and
         * second terciles of the array. Note that pivot1 <= pivot2.
         *
         * The pivots are stored in local variables, and the first and
         * the last of the sorted elements are moved to the locations
         * formerly occupied by the pivots. When partitioning is complete,
         * the pivots are swapped back into their final positions, and
         * excluded from subsequent sorting.
         */
        long pivot1 = a[e2]; a[e2] = a[left];
        long pivot2 = a[e4]; a[e4] = a[right];

        /*
         * Partitioning
         *
         *   left part         center part                  right part
         * ------------------------------------------------------------
         * [ < pivot1  |  pivot1 <= && <= pivot2  |   ?   |  > pivot2 ]
         * ------------------------------------------------------------
         *              ^                          ^     ^
         *              |                          |     |
         *             less                        k   great
         */

        // Pointers
        int less  = left  + 1; // The index of first element of center part
        int great = right - 1; // The index before first element of right part

        boolean pivotsDiffer = pivot1 != pivot2;

        if (pivotsDiffer) {
            /*
             * Invariants:
             *              all in (left, less)   < pivot1
             *    pivot1 <= all in [less, k)     <= pivot2
             *              all in (great, right) > pivot2
             *
             * Pointer k is the first index of ?-part
             */
            for (int k = less; k <= great; k++) {
                long ak = a[k];

                if (ak < pivot1) {
                    a[k] = a[less];
                    a[less++] = ak;
                } else if (ak > pivot2) {
                    while (a[great] > pivot2 && k < great) {
                        great--;
                    }
                    a[k] = a[great];
                    a[great--] = ak;
                    ak = a[k];

                    if (ak < pivot1) {
                        a[k] = a[less];
                        a[less++] = ak;
                    }
                }
            }
        } else { // Pivots are equal
            /*
             * Partition degenerates to the traditional 3-way
             * (or "Dutch National Flag") partition:
             *
             *   left part   center part            right part
             * -------------------------------------------------
             * [  < pivot  |  == pivot  |    ?    |  > pivot   ]
             * -------------------------------------------------
             *
             *              ^            ^       ^
             *              |            |       |
             *             less          k     great
             *
             * Invariants:
             *
             *   all in (left, less)   < pivot
             *   all in [less, k)     == pivot
             *   all in (great, right) > pivot
             *
             * Pointer k is the first index of ?-part
             */
            for (int k = less; k <= great; k++) {
                long ak = a[k];

                if (ak == pivot1) {
                  continue;
                }
                if (ak < pivot1) {
                    a[k] = a[less];
                    a[less++] = ak;
                } else {
                    while (a[great] > pivot1) {
                        great--;
                    }
                    a[k] = a[great];
                    a[great--] = ak;
                    ak = a[k];

                    if (ak < pivot1) {
                        a[k] = a[less];
                        a[less++] = ak;
                    }
                }
            }
        }

        // Swap pivots into their final positions
        a[left]  = a[less  - 1]; a[less  - 1] = pivot1;
        a[right] = a[great + 1]; a[great + 1] = pivot2;

        // Sort left and right parts recursively, excluding known pivot values
A
alanb 已提交
502 503
        doSort(a, left,   less - 2);
        doSort(a, great + 2, right);
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536

        /*
         * If pivot1 == pivot2, all elements from center
         * part are equal and, therefore, already sorted
         */
        if (!pivotsDiffer) {
            return;
        }

        /*
         * If center part is too large (comprises > 5/6 of
         * the array), swap internal pivot values to ends
         */
        if (less < e1 && e5 < great) {
            while (a[less] == pivot1) {
                less++;
            }
            for (int k = less + 1; k <= great; k++) {
                if (a[k] == pivot1) {
                    a[k] = a[less];
                    a[less++] = pivot1;
                }
            }
            while (a[great] == pivot2) {
                great--;
            }
            for (int k = great - 1; k >= less; k--) {
                if (a[k] == pivot2) {
                    a[k] = a[great];
                    a[great--] = pivot2;
                }
            }
        }
537 538

        // Sort center part recursively, excluding known pivot values
A
alanb 已提交
539 540 541 542 543 544 545 546 547 548
        doSort(a, less, great);
    }

    /**
     * Sorts the specified array into ascending numerical order.
     *
     * @param a the array to be sorted
     */
    public static void sort(short[] a) {
        doSort(a, 0, a.length - 1);
549 550
    }

A
alanb 已提交
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
    /**
     * Sorts the specified range of the array into ascending order. The range
     * to be sorted extends from the index {@code fromIndex}, inclusive, to
     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
     * the range to be sorted is empty.
     *
     * @param a the array to be sorted
     * @param fromIndex the index of the first element, inclusive, to be sorted
     * @param toIndex the index of the last element, exclusive, to be sorted
     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
     * @throws ArrayIndexOutOfBoundsException
     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
     */
    public static void sort(short[] a, int fromIndex, int toIndex) {
        rangeCheck(a.length, fromIndex, toIndex);
        doSort(a, fromIndex, toIndex - 1);
    }

    /** The number of distinct short values. */
570 571 572
    private static final int NUM_SHORT_VALUES = 1 << 16;

    /**
A
alanb 已提交
573 574 575 576
     * Sorts the specified range of the array into ascending order. This
     * method differs from the public {@code sort} method in that the
     * {@code right} index is inclusive, and it does no range checking on
     * {@code left} or {@code right}.
577 578
     *
     * @param a the array to be sorted
A
alanb 已提交
579 580
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
581
     */
A
alanb 已提交
582
    private static void doSort(short[] a, int left, int right) {
583 584 585 586 587 588 589 590 591 592 593
        // Use insertion sort on tiny arrays
        if (right - left + 1 < INSERTION_SORT_THRESHOLD) {
            for (int k = left + 1; k <= right; k++) {
                short ak = a[k];
                int j;

                for (j = k - 1; j >= left && ak < a[j]; j--) {
                    a[j + 1] = a[j];
                }
                a[j + 1] = ak;
            }
A
alanb 已提交
594
        } else if (right-left+1 > COUNTING_SORT_THRESHOLD_FOR_SHORT_OR_CHAR) {
595 596 597 598 599 600
            // Use counting sort on huge arrays
            int[] count = new int[NUM_SHORT_VALUES];

            for (int i = left; i <= right; i++) {
                count[a[i] - Short.MIN_VALUE]++;
            }
601
            for (int i = 0, k = left; i < count.length && k <= right; i++) {
602 603 604 605 606 607 608 609 610 611 612 613
                short value = (short) (i + Short.MIN_VALUE);

                for (int s = count[i]; s > 0; s--) {
                    a[k++] = value;
               }
            }
        } else { // Use Dual-Pivot Quicksort on large arrays
            dualPivotQuicksort(a, left, right);
        }
    }

    /**
A
alanb 已提交
614 615
     * Sorts the specified range of the array into ascending order by the
     * Dual-Pivot Quicksort algorithm.
616 617
     *
     * @param a the array to be sorted
A
alanb 已提交
618 619
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
     */
    private static void dualPivotQuicksort(short[] a, int left, int right) {
        // Compute indices of five evenly spaced elements
        int sixth = (right - left + 1) / 6;
        int e1 = left  + sixth;
        int e5 = right - sixth;
        int e3 = (left + right) >>> 1; // The midpoint
        int e4 = e3 + sixth;
        int e2 = e3 - sixth;

        // Sort these elements in place using a 5-element sorting network
        if (a[e1] > a[e2]) { short t = a[e1]; a[e1] = a[e2]; a[e2] = t; }
        if (a[e4] > a[e5]) { short t = a[e4]; a[e4] = a[e5]; a[e5] = t; }
        if (a[e1] > a[e3]) { short t = a[e1]; a[e1] = a[e3]; a[e3] = t; }
        if (a[e2] > a[e3]) { short t = a[e2]; a[e2] = a[e3]; a[e3] = t; }
        if (a[e1] > a[e4]) { short t = a[e1]; a[e1] = a[e4]; a[e4] = t; }
        if (a[e3] > a[e4]) { short t = a[e3]; a[e3] = a[e4]; a[e4] = t; }
        if (a[e2] > a[e5]) { short t = a[e2]; a[e2] = a[e5]; a[e5] = t; }
        if (a[e2] > a[e3]) { short t = a[e2]; a[e2] = a[e3]; a[e3] = t; }
        if (a[e4] > a[e5]) { short t = a[e4]; a[e4] = a[e5]; a[e5] = t; }

        /*
         * Use the second and fourth of the five sorted elements as pivots.
         * These values are inexpensive approximations of the first and
         * second terciles of the array. Note that pivot1 <= pivot2.
         *
         * The pivots are stored in local variables, and the first and
         * the last of the sorted elements are moved to the locations
         * formerly occupied by the pivots. When partitioning is complete,
         * the pivots are swapped back into their final positions, and
         * excluded from subsequent sorting.
         */
        short pivot1 = a[e2]; a[e2] = a[left];
        short pivot2 = a[e4]; a[e4] = a[right];

        /*
         * Partitioning
         *
         *   left part         center part                  right part
         * ------------------------------------------------------------
         * [ < pivot1  |  pivot1 <= && <= pivot2  |   ?   |  > pivot2 ]
         * ------------------------------------------------------------
         *              ^                          ^     ^
         *              |                          |     |
         *             less                        k   great
         */

        // Pointers
        int less  = left  + 1; // The index of first element of center part
        int great = right - 1; // The index before first element of right part

        boolean pivotsDiffer = pivot1 != pivot2;

        if (pivotsDiffer) {
            /*
             * Invariants:
             *              all in (left, less)   < pivot1
             *    pivot1 <= all in [less, k)     <= pivot2
             *              all in (great, right) > pivot2
             *
             * Pointer k is the first index of ?-part
             */
            for (int k = less; k <= great; k++) {
                short ak = a[k];

                if (ak < pivot1) {
                    a[k] = a[less];
                    a[less++] = ak;
                } else if (ak > pivot2) {
                    while (a[great] > pivot2 && k < great) {
                        great--;
                    }
                    a[k] = a[great];
                    a[great--] = ak;
                    ak = a[k];

                    if (ak < pivot1) {
                        a[k] = a[less];
                        a[less++] = ak;
                    }
                }
            }
        } else { // Pivots are equal
            /*
             * Partition degenerates to the traditional 3-way
             * (or "Dutch National Flag") partition:
             *
             *   left part   center part            right part
             * -------------------------------------------------
             * [  < pivot  |  == pivot  |    ?    |  > pivot   ]
             * -------------------------------------------------
             *
             *              ^            ^       ^
             *              |            |       |
             *             less          k     great
             *
             * Invariants:
             *
             *   all in (left, less)   < pivot
             *   all in [less, k)     == pivot
             *   all in (great, right) > pivot
             *
             * Pointer k is the first index of ?-part
             */
            for (int k = less; k <= great; k++) {
                short ak = a[k];

                if (ak == pivot1) {
                  continue;
                }
                if (ak < pivot1) {
                    a[k] = a[less];
                    a[less++] = ak;
                } else {
                    while (a[great] > pivot1) {
                        great--;
                    }
                    a[k] = a[great];
                    a[great--] = ak;
                    ak = a[k];

                    if (ak < pivot1) {
                        a[k] = a[less];
                        a[less++] = ak;
                    }
                }
            }
        }

        // Swap pivots into their final positions
        a[left]  = a[less  - 1]; a[less  - 1] = pivot1;
        a[right] = a[great + 1]; a[great + 1] = pivot2;

        // Sort left and right parts recursively, excluding known pivot values
A
alanb 已提交
754 755
        doSort(a, left,   less - 2);
        doSort(a, great + 2, right);
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790

        /*
         * If pivot1 == pivot2, all elements from center
         * part are equal and, therefore, already sorted
         */
        if (!pivotsDiffer) {
            return;
        }

        /*
         * If center part is too large (comprises > 5/6 of
         * the array), swap internal pivot values to ends
         */
        if (less < e1 && e5 < great) {
            while (a[less] == pivot1) {
                less++;
            }
            for (int k = less + 1; k <= great; k++) {
                if (a[k] == pivot1) {
                    a[k] = a[less];
                    a[less++] = pivot1;
                }
            }
            while (a[great] == pivot2) {
                great--;
            }
            for (int k = great - 1; k >= less; k--) {
                if (a[k] == pivot2) {
                    a[k] = a[great];
                    a[great--] = pivot2;
                }
            }
        }

        // Sort center part recursively, excluding known pivot values
A
alanb 已提交
791
        doSort(a, less, great);
792 793
    }

A
alanb 已提交
794 795 796 797 798 799 800 801
    /**
     * Sorts the specified array into ascending numerical order.
     *
     * @param a the array to be sorted
     */
    public static void sort(char[] a) {
        doSort(a, 0, a.length - 1);
    }
802 803

    /**
A
alanb 已提交
804 805 806 807
     * Sorts the specified range of the array into ascending order. The range
     * to be sorted extends from the index {@code fromIndex}, inclusive, to
     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
     * the range to be sorted is empty.
808 809
     *
     * @param a the array to be sorted
A
alanb 已提交
810 811 812 813 814
     * @param fromIndex the index of the first element, inclusive, to be sorted
     * @param toIndex the index of the last element, exclusive, to be sorted
     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
     * @throws ArrayIndexOutOfBoundsException
     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
815
     */
A
alanb 已提交
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
    public static void sort(char[] a, int fromIndex, int toIndex) {
        rangeCheck(a.length, fromIndex, toIndex);
        doSort(a, fromIndex, toIndex - 1);
    }

    /** The number of distinct char values. */
    private static final int NUM_CHAR_VALUES = 1 << 16;

    /**
     * Sorts the specified range of the array into ascending order. This
     * method differs from the public {@code sort} method in that the
     * {@code right} index is inclusive, and it does no range checking on
     * {@code left} or {@code right}.
     *
     * @param a the array to be sorted
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
     */
    private static void doSort(char[] a, int left, int right) {
835 836 837
        // Use insertion sort on tiny arrays
        if (right - left + 1 < INSERTION_SORT_THRESHOLD) {
            for (int k = left + 1; k <= right; k++) {
A
alanb 已提交
838
                char ak = a[k];
839 840 841 842 843 844 845
                int j;

                for (j = k - 1; j >= left && ak < a[j]; j--) {
                    a[j + 1] = a[j];
                }
                a[j + 1] = ak;
            }
A
alanb 已提交
846
        } else if (right-left+1 > COUNTING_SORT_THRESHOLD_FOR_SHORT_OR_CHAR) {
847
            // Use counting sort on huge arrays
A
alanb 已提交
848
            int[] count = new int[NUM_CHAR_VALUES];
849 850

            for (int i = left; i <= right; i++) {
A
alanb 已提交
851
                count[a[i]]++;
852
            }
853
            for (int i = 0, k = left; i < count.length && k <= right; i++) {
854
                for (int s = count[i]; s > 0; s--) {
A
alanb 已提交
855
                    a[k++] = (char) i;
856 857 858 859 860 861 862 863
               }
            }
        } else { // Use Dual-Pivot Quicksort on large arrays
            dualPivotQuicksort(a, left, right);
        }
    }

    /**
A
alanb 已提交
864 865
     * Sorts the specified range of the array into ascending order by the
     * Dual-Pivot Quicksort algorithm.
866 867
     *
     * @param a the array to be sorted
A
alanb 已提交
868 869
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
870
     */
A
alanb 已提交
871
    private static void dualPivotQuicksort(char[] a, int left, int right) {
872 873 874 875 876 877 878 879 880
        // Compute indices of five evenly spaced elements
        int sixth = (right - left + 1) / 6;
        int e1 = left  + sixth;
        int e5 = right - sixth;
        int e3 = (left + right) >>> 1; // The midpoint
        int e4 = e3 + sixth;
        int e2 = e3 - sixth;

        // Sort these elements in place using a 5-element sorting network
A
alanb 已提交
881 882 883 884 885 886 887 888 889
        if (a[e1] > a[e2]) { char t = a[e1]; a[e1] = a[e2]; a[e2] = t; }
        if (a[e4] > a[e5]) { char t = a[e4]; a[e4] = a[e5]; a[e5] = t; }
        if (a[e1] > a[e3]) { char t = a[e1]; a[e1] = a[e3]; a[e3] = t; }
        if (a[e2] > a[e3]) { char t = a[e2]; a[e2] = a[e3]; a[e3] = t; }
        if (a[e1] > a[e4]) { char t = a[e1]; a[e1] = a[e4]; a[e4] = t; }
        if (a[e3] > a[e4]) { char t = a[e3]; a[e3] = a[e4]; a[e4] = t; }
        if (a[e2] > a[e5]) { char t = a[e2]; a[e2] = a[e5]; a[e5] = t; }
        if (a[e2] > a[e3]) { char t = a[e2]; a[e2] = a[e3]; a[e3] = t; }
        if (a[e4] > a[e5]) { char t = a[e4]; a[e4] = a[e5]; a[e5] = t; }
890 891 892 893 894 895 896 897 898 899 900 901

        /*
         * Use the second and fourth of the five sorted elements as pivots.
         * These values are inexpensive approximations of the first and
         * second terciles of the array. Note that pivot1 <= pivot2.
         *
         * The pivots are stored in local variables, and the first and
         * the last of the sorted elements are moved to the locations
         * formerly occupied by the pivots. When partitioning is complete,
         * the pivots are swapped back into their final positions, and
         * excluded from subsequent sorting.
         */
A
alanb 已提交
902 903
        char pivot1 = a[e2]; a[e2] = a[left];
        char pivot2 = a[e4]; a[e4] = a[right];
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932

        /*
         * Partitioning
         *
         *   left part         center part                  right part
         * ------------------------------------------------------------
         * [ < pivot1  |  pivot1 <= && <= pivot2  |   ?   |  > pivot2 ]
         * ------------------------------------------------------------
         *              ^                          ^     ^
         *              |                          |     |
         *             less                        k   great
         */

        // Pointers
        int less  = left  + 1; // The index of first element of center part
        int great = right - 1; // The index before first element of right part

        boolean pivotsDiffer = pivot1 != pivot2;

        if (pivotsDiffer) {
            /*
             * Invariants:
             *              all in (left, less)   < pivot1
             *    pivot1 <= all in [less, k)     <= pivot2
             *              all in (great, right) > pivot2
             *
             * Pointer k is the first index of ?-part
             */
            for (int k = less; k <= great; k++) {
A
alanb 已提交
933
                char ak = a[k];
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974

                if (ak < pivot1) {
                    a[k] = a[less];
                    a[less++] = ak;
                } else if (ak > pivot2) {
                    while (a[great] > pivot2 && k < great) {
                        great--;
                    }
                    a[k] = a[great];
                    a[great--] = ak;
                    ak = a[k];

                    if (ak < pivot1) {
                        a[k] = a[less];
                        a[less++] = ak;
                    }
                }
            }
        } else { // Pivots are equal
            /*
             * Partition degenerates to the traditional 3-way
             * (or "Dutch National Flag") partition:
             *
             *   left part   center part            right part
             * -------------------------------------------------
             * [  < pivot  |  == pivot  |    ?    |  > pivot   ]
             * -------------------------------------------------
             *
             *              ^            ^       ^
             *              |            |       |
             *             less          k     great
             *
             * Invariants:
             *
             *   all in (left, less)   < pivot
             *   all in [less, k)     == pivot
             *   all in (great, right) > pivot
             *
             * Pointer k is the first index of ?-part
             */
            for (int k = less; k <= great; k++) {
A
alanb 已提交
975
                char ak = a[k];
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003

                if (ak == pivot1) {
                  continue;
                }
                if (ak < pivot1) {
                    a[k] = a[less];
                    a[less++] = ak;
                } else {
                    while (a[great] > pivot1) {
                        great--;
                    }
                    a[k] = a[great];
                    a[great--] = ak;
                    ak = a[k];

                    if (ak < pivot1) {
                        a[k] = a[less];
                        a[less++] = ak;
                    }
                }
            }
        }

        // Swap pivots into their final positions
        a[left]  = a[less  - 1]; a[less  - 1] = pivot1;
        a[right] = a[great + 1]; a[great + 1] = pivot2;

        // Sort left and right parts recursively, excluding known pivot values
A
alanb 已提交
1004 1005
        doSort(a, left,   less - 2);
        doSort(a, great + 2, right);
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040

        /*
         * If pivot1 == pivot2, all elements from center
         * part are equal and, therefore, already sorted
         */
        if (!pivotsDiffer) {
            return;
        }

        /*
         * If center part is too large (comprises > 5/6 of
         * the array), swap internal pivot values to ends
         */
        if (less < e1 && e5 < great) {
            while (a[less] == pivot1) {
                less++;
            }
            for (int k = less + 1; k <= great; k++) {
                if (a[k] == pivot1) {
                    a[k] = a[less];
                    a[less++] = pivot1;
                }
            }
            while (a[great] == pivot2) {
                great--;
            }
            for (int k = great - 1; k >= less; k--) {
                if (a[k] == pivot2) {
                    a[k] = a[great];
                    a[great--] = pivot2;
                }
            }
        }

        // Sort center part recursively, excluding known pivot values
A
alanb 已提交
1041
        doSort(a, less, great);
1042 1043
    }

A
alanb 已提交
1044 1045 1046 1047 1048 1049 1050 1051
    /**
     * Sorts the specified array into ascending numerical order.
     *
     * @param a the array to be sorted
     */
    public static void sort(byte[] a) {
        doSort(a, 0, a.length - 1);
    }
1052 1053

    /**
A
alanb 已提交
1054 1055 1056 1057
     * Sorts the specified range of the array into ascending order. The range
     * to be sorted extends from the index {@code fromIndex}, inclusive, to
     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
     * the range to be sorted is empty.
1058 1059
     *
     * @param a the array to be sorted
A
alanb 已提交
1060 1061 1062 1063 1064
     * @param fromIndex the index of the first element, inclusive, to be sorted
     * @param toIndex the index of the last element, exclusive, to be sorted
     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
     * @throws ArrayIndexOutOfBoundsException
     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
1065
     */
A
alanb 已提交
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
    public static void sort(byte[] a, int fromIndex, int toIndex) {
        rangeCheck(a.length, fromIndex, toIndex);
        doSort(a, fromIndex, toIndex - 1);
    }

    /** The number of distinct byte values. */
    private static final int NUM_BYTE_VALUES = 1 << 8;

    /**
     * Sorts the specified range of the array into ascending order. This
     * method differs from the public {@code sort} method in that the
     * {@code right} index is inclusive, and it does no range checking on
     * {@code left} or {@code right}.
     *
     * @param a the array to be sorted
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
     */
    private static void doSort(byte[] a, int left, int right) {
1085 1086 1087
        // Use insertion sort on tiny arrays
        if (right - left + 1 < INSERTION_SORT_THRESHOLD) {
            for (int k = left + 1; k <= right; k++) {
A
alanb 已提交
1088
                byte ak = a[k];
1089 1090 1091 1092 1093 1094 1095
                int j;

                for (j = k - 1; j >= left && ak < a[j]; j--) {
                    a[j + 1] = a[j];
                }
                a[j + 1] = ak;
            }
A
alanb 已提交
1096
        } else if (right - left + 1 > COUNTING_SORT_THRESHOLD_FOR_BYTE) {
1097
            // Use counting sort on huge arrays
A
alanb 已提交
1098
            int[] count = new int[NUM_BYTE_VALUES];
1099 1100

            for (int i = left; i <= right; i++) {
A
alanb 已提交
1101
                count[a[i] - Byte.MIN_VALUE]++;
1102
            }
1103
            for (int i = 0, k = left; i < count.length && k <= right; i++) {
A
alanb 已提交
1104 1105
                byte value = (byte) (i + Byte.MIN_VALUE);

1106
                for (int s = count[i]; s > 0; s--) {
A
alanb 已提交
1107
                    a[k++] = value;
1108 1109 1110 1111 1112 1113 1114 1115
               }
            }
        } else { // Use Dual-Pivot Quicksort on large arrays
            dualPivotQuicksort(a, left, right);
        }
    }

    /**
A
alanb 已提交
1116 1117
     * Sorts the specified range of the array into ascending order by the
     * Dual-Pivot Quicksort algorithm.
1118 1119
     *
     * @param a the array to be sorted
A
alanb 已提交
1120 1121
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
1122
     */
A
alanb 已提交
1123
    private static void dualPivotQuicksort(byte[] a, int left, int right) {
1124 1125 1126 1127 1128 1129 1130 1131 1132
        // Compute indices of five evenly spaced elements
        int sixth = (right - left + 1) / 6;
        int e1 = left  + sixth;
        int e5 = right - sixth;
        int e3 = (left + right) >>> 1; // The midpoint
        int e4 = e3 + sixth;
        int e2 = e3 - sixth;

        // Sort these elements in place using a 5-element sorting network
A
alanb 已提交
1133 1134 1135 1136 1137 1138 1139 1140 1141
        if (a[e1] > a[e2]) { byte t = a[e1]; a[e1] = a[e2]; a[e2] = t; }
        if (a[e4] > a[e5]) { byte t = a[e4]; a[e4] = a[e5]; a[e5] = t; }
        if (a[e1] > a[e3]) { byte t = a[e1]; a[e1] = a[e3]; a[e3] = t; }
        if (a[e2] > a[e3]) { byte t = a[e2]; a[e2] = a[e3]; a[e3] = t; }
        if (a[e1] > a[e4]) { byte t = a[e1]; a[e1] = a[e4]; a[e4] = t; }
        if (a[e3] > a[e4]) { byte t = a[e3]; a[e3] = a[e4]; a[e4] = t; }
        if (a[e2] > a[e5]) { byte t = a[e2]; a[e2] = a[e5]; a[e5] = t; }
        if (a[e2] > a[e3]) { byte t = a[e2]; a[e2] = a[e3]; a[e3] = t; }
        if (a[e4] > a[e5]) { byte t = a[e4]; a[e4] = a[e5]; a[e5] = t; }
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153

        /*
         * Use the second and fourth of the five sorted elements as pivots.
         * These values are inexpensive approximations of the first and
         * second terciles of the array. Note that pivot1 <= pivot2.
         *
         * The pivots are stored in local variables, and the first and
         * the last of the sorted elements are moved to the locations
         * formerly occupied by the pivots. When partitioning is complete,
         * the pivots are swapped back into their final positions, and
         * excluded from subsequent sorting.
         */
A
alanb 已提交
1154 1155
        byte pivot1 = a[e2]; a[e2] = a[left];
        byte pivot2 = a[e4]; a[e4] = a[right];
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184

        /*
         * Partitioning
         *
         *   left part         center part                  right part
         * ------------------------------------------------------------
         * [ < pivot1  |  pivot1 <= && <= pivot2  |   ?   |  > pivot2 ]
         * ------------------------------------------------------------
         *              ^                          ^     ^
         *              |                          |     |
         *             less                        k   great
         */

        // Pointers
        int less  = left  + 1; // The index of first element of center part
        int great = right - 1; // The index before first element of right part

        boolean pivotsDiffer = pivot1 != pivot2;

        if (pivotsDiffer) {
            /*
             * Invariants:
             *              all in (left, less)   < pivot1
             *    pivot1 <= all in [less, k)     <= pivot2
             *              all in (great, right) > pivot2
             *
             * Pointer k is the first index of ?-part
             */
            for (int k = less; k <= great; k++) {
A
alanb 已提交
1185
                byte ak = a[k];
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226

                if (ak < pivot1) {
                    a[k] = a[less];
                    a[less++] = ak;
                } else if (ak > pivot2) {
                    while (a[great] > pivot2 && k < great) {
                        great--;
                    }
                    a[k] = a[great];
                    a[great--] = ak;
                    ak = a[k];

                    if (ak < pivot1) {
                        a[k] = a[less];
                        a[less++] = ak;
                    }
                }
            }
        } else { // Pivots are equal
            /*
             * Partition degenerates to the traditional 3-way
             * (or "Dutch National Flag") partition:
             *
             *   left part   center part            right part
             * -------------------------------------------------
             * [  < pivot  |  == pivot  |    ?    |  > pivot   ]
             * -------------------------------------------------
             *
             *              ^            ^       ^
             *              |            |       |
             *             less          k     great
             *
             * Invariants:
             *
             *   all in (left, less)   < pivot
             *   all in [less, k)     == pivot
             *   all in (great, right) > pivot
             *
             * Pointer k is the first index of ?-part
             */
            for (int k = less; k <= great; k++) {
A
alanb 已提交
1227
                byte ak = a[k];
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255

                if (ak == pivot1) {
                  continue;
                }
                if (ak < pivot1) {
                    a[k] = a[less];
                    a[less++] = ak;
                } else {
                    while (a[great] > pivot1) {
                        great--;
                    }
                    a[k] = a[great];
                    a[great--] = ak;
                    ak = a[k];

                    if (ak < pivot1) {
                        a[k] = a[less];
                        a[less++] = ak;
                    }
                }
            }
        }

        // Swap pivots into their final positions
        a[left]  = a[less  - 1]; a[less  - 1] = pivot1;
        a[right] = a[great + 1]; a[great + 1] = pivot2;

        // Sort left and right parts recursively, excluding known pivot values
A
alanb 已提交
1256 1257
        doSort(a, left,   less - 2);
        doSort(a, great + 2, right);
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292

        /*
         * If pivot1 == pivot2, all elements from center
         * part are equal and, therefore, already sorted
         */
        if (!pivotsDiffer) {
            return;
        }

        /*
         * If center part is too large (comprises > 5/6 of
         * the array), swap internal pivot values to ends
         */
        if (less < e1 && e5 < great) {
            while (a[less] == pivot1) {
                less++;
            }
            for (int k = less + 1; k <= great; k++) {
                if (a[k] == pivot1) {
                    a[k] = a[less];
                    a[less++] = pivot1;
                }
            }
            while (a[great] == pivot2) {
                great--;
            }
            for (int k = great - 1; k >= less; k--) {
                if (a[k] == pivot2) {
                    a[k] = a[great];
                    a[great--] = pivot2;
                }
            }
        }

        // Sort center part recursively, excluding known pivot values
A
alanb 已提交
1293
        doSort(a, less, great);
1294 1295 1296
    }

    /**
A
alanb 已提交
1297 1298 1299 1300 1301 1302 1303 1304 1305
     * Sorts the specified array into ascending numerical order.
     *
     * <p>The {@code <} relation does not provide a total order on all float
     * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
     * value compares neither less than, greater than, nor equal to any value,
     * even itself. This method uses the total order imposed by the method
     * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
     * {@code 0.0f} and {@code Float.NaN} is considered greater than any
     * other value and all {@code Float.NaN} values are considered equal.
1306 1307 1308
     *
     * @param a the array to be sorted
     */
A
alanb 已提交
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
    public static void sort(float[] a) {
        sortNegZeroAndNaN(a, 0, a.length - 1);
    }

    /**
     * Sorts the specified range of the array into ascending order. The range
     * to be sorted extends from the index {@code fromIndex}, inclusive, to
     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
     * the range to be sorted is empty.
     *
     * <p>The {@code <} relation does not provide a total order on all float
     * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
     * value compares neither less than, greater than, nor equal to any value,
     * even itself. This method uses the total order imposed by the method
     * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
     * {@code 0.0f} and {@code Float.NaN} is considered greater than any
     * other value and all {@code Float.NaN} values are considered equal.
     *
     * @param a the array to be sorted
     * @param fromIndex the index of the first element, inclusive, to be sorted
     * @param toIndex the index of the last element, exclusive, to be sorted
     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
     * @throws ArrayIndexOutOfBoundsException
     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
     */
    public static void sort(float[] a, int fromIndex, int toIndex) {
        rangeCheck(a.length, fromIndex, toIndex);
        sortNegZeroAndNaN(a, fromIndex, toIndex - 1);
    }

    /**
     * Sorts the specified range of the array into ascending order. The
     * sort is done in three phases to avoid expensive comparisons in the
     * inner loop. The comparisons would be expensive due to anomalies
     * associated with negative zero {@code -0.0f} and {@code Float.NaN}.
     *
     * @param a the array to be sorted
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
     */
    private static void sortNegZeroAndNaN(float[] a, int left, int right) {
        /*
         * Phase 1: Count negative zeros and move NaNs to end of array
         */
        final int NEGATIVE_ZERO = Float.floatToIntBits(-0.0f);
        int numNegativeZeros = 0;
        int n = right;

        for (int k = left; k <= n; k++) {
            float ak = a[k];

            if (ak == 0.0f && NEGATIVE_ZERO == Float.floatToIntBits(ak)) {
                a[k] = 0.0f;
                numNegativeZeros++;
            } else if (ak != ak) { // i.e., ak is NaN
                a[k--] = a[n];
                a[n--] = Float.NaN;
            }
        }

        /*
         * Phase 2: Sort everything except NaNs (which are already in place)
         */
        doSort(a, left, n);

        /*
         * Phase 3: Turn positive zeros back into negative zeros as appropriate
         */
        if (numNegativeZeros == 0) {
            return;
        }

        // Find first zero element
        int zeroIndex = findAnyZero(a, left, n);

        for (int i = zeroIndex - 1; i >= left && a[i] == 0.0f; i--) {
            zeroIndex = i;
        }

        // Turn the right number of positive zeros back into negative zeros
        for (int i = zeroIndex, m = zeroIndex + numNegativeZeros; i < m; i++) {
            a[i] = -0.0f;
        }
    }

    /**
     * Returns the index of some zero element in the specified range via
     * binary search. The range is assumed to be sorted, and must contain
     * at least one zero.
     *
     * @param a the array to be searched
     * @param low the index of the first element, inclusive, to be searched
     * @param high the index of the last element, inclusive, to be searched
     */
    private static int findAnyZero(float[] a, int low, int high) {
        while (true) {
            int middle = (low + high) >>> 1;
            float middleValue = a[middle];

            if (middleValue < 0.0f) {
                low = middle + 1;
            } else if (middleValue > 0.0f) {
                high = middle - 1;
            } else { // middleValue == 0.0f
                return middle;
            }
        }
    }

    /**
     * Sorts the specified range of the array into ascending order. This
     * method differs from the public {@code sort} method in three ways:
     * {@code right} index is inclusive, it does no range checking on
     * {@code left} or {@code right}, and it does not handle negative
     * zeros or NaNs in the array.
     *
     * @param a the array to be sorted, which must not contain -0.0f or NaN
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
     */
    private static void doSort(float[] a, int left, int right) {
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
        // Use insertion sort on tiny arrays
        if (right - left + 1 < INSERTION_SORT_THRESHOLD) {
            for (int k = left + 1; k <= right; k++) {
                float ak = a[k];
                int j;

                for (j = k - 1; j >= left && ak < a[j]; j--) {
                    a[j + 1] = a[j];
                }
                a[j + 1] = ak;
            }
        } else { // Use Dual-Pivot Quicksort on large arrays
            dualPivotQuicksort(a, left, right);
        }
    }

    /**
A
alanb 已提交
1447 1448
     * Sorts the specified range of the array into ascending order by the
     * Dual-Pivot Quicksort algorithm.
1449 1450
     *
     * @param a the array to be sorted
A
alanb 已提交
1451 1452
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
     */
    private static void dualPivotQuicksort(float[] a, int left, int right) {
        // Compute indices of five evenly spaced elements
        int sixth = (right - left + 1) / 6;
        int e1 = left  + sixth;
        int e5 = right - sixth;
        int e3 = (left + right) >>> 1; // The midpoint
        int e4 = e3 + sixth;
        int e2 = e3 - sixth;

        // Sort these elements in place using a 5-element sorting network
        if (a[e1] > a[e2]) { float t = a[e1]; a[e1] = a[e2]; a[e2] = t; }
        if (a[e4] > a[e5]) { float t = a[e4]; a[e4] = a[e5]; a[e5] = t; }
        if (a[e1] > a[e3]) { float t = a[e1]; a[e1] = a[e3]; a[e3] = t; }
        if (a[e2] > a[e3]) { float t = a[e2]; a[e2] = a[e3]; a[e3] = t; }
        if (a[e1] > a[e4]) { float t = a[e1]; a[e1] = a[e4]; a[e4] = t; }
        if (a[e3] > a[e4]) { float t = a[e3]; a[e3] = a[e4]; a[e4] = t; }
        if (a[e2] > a[e5]) { float t = a[e2]; a[e2] = a[e5]; a[e5] = t; }
        if (a[e2] > a[e3]) { float t = a[e2]; a[e2] = a[e3]; a[e3] = t; }
        if (a[e4] > a[e5]) { float t = a[e4]; a[e4] = a[e5]; a[e5] = t; }

        /*
         * Use the second and fourth of the five sorted elements as pivots.
         * These values are inexpensive approximations of the first and
         * second terciles of the array. Note that pivot1 <= pivot2.
         *
         * The pivots are stored in local variables, and the first and
         * the last of the sorted elements are moved to the locations
         * formerly occupied by the pivots. When partitioning is complete,
         * the pivots are swapped back into their final positions, and
         * excluded from subsequent sorting.
         */
        float pivot1 = a[e2]; a[e2] = a[left];
        float pivot2 = a[e4]; a[e4] = a[right];

        /*
         * Partitioning
         *
         *   left part         center part                  right part
         * ------------------------------------------------------------
         * [ < pivot1  |  pivot1 <= && <= pivot2  |   ?   |  > pivot2 ]
         * ------------------------------------------------------------
         *              ^                          ^     ^
         *              |                          |     |
         *             less                        k   great
         */

        // Pointers
        int less  = left  + 1; // The index of first element of center part
        int great = right - 1; // The index before first element of right part

        boolean pivotsDiffer = pivot1 != pivot2;

        if (pivotsDiffer) {
            /*
             * Invariants:
             *              all in (left, less)   < pivot1
             *    pivot1 <= all in [less, k)     <= pivot2
             *              all in (great, right) > pivot2
             *
             * Pointer k is the first index of ?-part
             */
            for (int k = less; k <= great; k++) {
                float ak = a[k];

                if (ak < pivot1) {
                    a[k] = a[less];
                    a[less++] = ak;
                } else if (ak > pivot2) {
                    while (a[great] > pivot2 && k < great) {
                        great--;
                    }
                    a[k] = a[great];
                    a[great--] = ak;
                    ak = a[k];

                    if (ak < pivot1) {
                        a[k] = a[less];
                        a[less++] = ak;
                    }
                }
            }
        } else { // Pivots are equal
            /*
             * Partition degenerates to the traditional 3-way
             * (or "Dutch National Flag") partition:
             *
             *   left part   center part            right part
             * -------------------------------------------------
             * [  < pivot  |  == pivot  |    ?    |  > pivot   ]
             * -------------------------------------------------
             *
             *              ^            ^       ^
             *              |            |       |
             *             less          k     great
             *
             * Invariants:
             *
             *   all in (left, less)   < pivot
             *   all in [less, k)     == pivot
             *   all in (great, right) > pivot
             *
             * Pointer k is the first index of ?-part
             */
            for (int k = less; k <= great; k++) {
                float ak = a[k];

                if (ak == pivot1) {
                  continue;
                }
                if (ak < pivot1) {
                    a[k] = a[less];
                    a[less++] = ak;
                } else {
                    while (a[great] > pivot1) {
                        great--;
                    }
                    a[k] = a[great];
                    a[great--] = ak;
                    ak = a[k];

                    if (ak < pivot1) {
                        a[k] = a[less];
                        a[less++] = ak;
                    }
                }
            }
        }

        // Swap pivots into their final positions
        a[left]  = a[less  - 1]; a[less  - 1] = pivot1;
        a[right] = a[great + 1]; a[great + 1] = pivot2;

        // Sort left and right parts recursively, excluding known pivot values
A
alanb 已提交
1587 1588
        doSort(a, left,   less - 2);
        doSort(a, great + 2, right);
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623

        /*
         * If pivot1 == pivot2, all elements from center
         * part are equal and, therefore, already sorted
         */
        if (!pivotsDiffer) {
            return;
        }

        /*
         * If center part is too large (comprises > 5/6 of
         * the array), swap internal pivot values to ends
         */
        if (less < e1 && e5 < great) {
            while (a[less] == pivot1) {
                less++;
            }
            for (int k = less + 1; k <= great; k++) {
                if (a[k] == pivot1) {
                    a[k] = a[less];
                    a[less++] = pivot1;
                }
            }
            while (a[great] == pivot2) {
                great--;
            }
            for (int k = great - 1; k >= less; k--) {
                if (a[k] == pivot2) {
                    a[k] = a[great];
                    a[great--] = pivot2;
                }
            }
        }

        // Sort center part recursively, excluding known pivot values
A
alanb 已提交
1624
        doSort(a, less, great);
1625 1626 1627
    }

    /**
A
alanb 已提交
1628 1629 1630 1631 1632 1633 1634 1635 1636
     * Sorts the specified array into ascending numerical order.
     *
     * <p>The {@code <} relation does not provide a total order on all double
     * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
     * value compares neither less than, greater than, nor equal to any value,
     * even itself. This method uses the total order imposed by the method
     * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
     * {@code 0.0d} and {@code Double.NaN} is considered greater than any
     * other value and all {@code Double.NaN} values are considered equal.
1637 1638 1639
     *
     * @param a the array to be sorted
     */
A
alanb 已提交
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
    public static void sort(double[] a) {
        sortNegZeroAndNaN(a, 0, a.length - 1);
    }

    /**
     * Sorts the specified range of the array into ascending order. The range
     * to be sorted extends from the index {@code fromIndex}, inclusive, to
     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
     * the range to be sorted is empty.
     *
     * <p>The {@code <} relation does not provide a total order on all double
     * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
     * value compares neither less than, greater than, nor equal to any value,
     * even itself. This method uses the total order imposed by the method
     * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
     * {@code 0.0d} and {@code Double.NaN} is considered greater than any
     * other value and all {@code Double.NaN} values are considered equal.
     *
     * @param a the array to be sorted
     * @param fromIndex the index of the first element, inclusive, to be sorted
     * @param toIndex the index of the last element, exclusive, to be sorted
     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
     * @throws ArrayIndexOutOfBoundsException
     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
     */
    public static void sort(double[] a, int fromIndex, int toIndex) {
        rangeCheck(a.length, fromIndex, toIndex);
        sortNegZeroAndNaN(a, fromIndex, toIndex - 1);
    }

    /**
     * Sorts the specified range of the array into ascending order. The
     * sort is done in three phases to avoid expensive comparisons in the
     * inner loop. The comparisons would be expensive due to anomalies
     * associated with negative zero {@code -0.0d} and {@code Double.NaN}.
     *
     * @param a the array to be sorted
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
     */
    private static void sortNegZeroAndNaN(double[] a, int left, int right) {
        /*
         * Phase 1: Count negative zeros and move NaNs to end of array
         */
        final long NEGATIVE_ZERO = Double.doubleToLongBits(-0.0d);
        int numNegativeZeros = 0;
        int n = right;

        for (int k = left; k <= n; k++) {
            double ak = a[k];

            if (ak == 0.0d && NEGATIVE_ZERO == Double.doubleToLongBits(ak)) {
                a[k] = 0.0d;
                numNegativeZeros++;
            } else if (ak != ak) { // i.e., ak is NaN
                a[k--] = a[n];
                a[n--] = Double.NaN;
            }
        }

        /*
         * Phase 2: Sort everything except NaNs (which are already in place)
         */
        doSort(a, left, n);

        /*
         * Phase 3: Turn positive zeros back into negative zeros as appropriate
         */
        if (numNegativeZeros == 0) {
            return;
        }

        // Find first zero element
        int zeroIndex = findAnyZero(a, left, n);

        for (int i = zeroIndex - 1; i >= left && a[i] == 0.0d; i--) {
            zeroIndex = i;
        }

        // Turn the right number of positive zeros back into negative zeros
        for (int i = zeroIndex, m = zeroIndex + numNegativeZeros; i < m; i++) {
            a[i] = -0.0d;
        }
    }

    /**
     * Returns the index of some zero element in the specified range via
     * binary search. The range is assumed to be sorted, and must contain
     * at least one zero.
     *
     * @param a the array to be searched
     * @param low the index of the first element, inclusive, to be searched
     * @param high the index of the last element, inclusive, to be searched
     */
    private static int findAnyZero(double[] a, int low, int high) {
        while (true) {
            int middle = (low + high) >>> 1;
            double middleValue = a[middle];

            if (middleValue < 0.0d) {
                low = middle + 1;
            } else if (middleValue > 0.0d) {
                high = middle - 1;
            } else { // middleValue == 0.0d
                return middle;
            }
        }
    }

    /**
     * Sorts the specified range of the array into ascending order. This
     * method differs from the public {@code sort} method in three ways:
     * {@code right} index is inclusive, it does no range checking on
     * {@code left} or {@code right}, and it does not handle negative
     * zeros or NaNs in the array.
     *
     * @param a the array to be sorted, which must not contain -0.0d and NaN
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
     */
    private static void doSort(double[] a, int left, int right) {
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
        // Use insertion sort on tiny arrays
        if (right - left + 1 < INSERTION_SORT_THRESHOLD) {
            for (int k = left + 1; k <= right; k++) {
                double ak = a[k];
                int j;

                for (j = k - 1; j >= left && ak < a[j]; j--) {
                    a[j + 1] = a[j];
                }
                a[j + 1] = ak;
            }
        } else { // Use Dual-Pivot Quicksort on large arrays
            dualPivotQuicksort(a, left, right);
        }
    }

    /**
A
alanb 已提交
1778 1779
     * Sorts the specified range of the array into ascending order by the
     * Dual-Pivot Quicksort algorithm.
1780 1781
     *
     * @param a the array to be sorted
A
alanb 已提交
1782 1783
     * @param left the index of the first element, inclusive, to be sorted
     * @param right the index of the last element, inclusive, to be sorted
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
     */
    private static void dualPivotQuicksort(double[] a, int left, int right) {
        // Compute indices of five evenly spaced elements
        int sixth = (right - left + 1) / 6;
        int e1 = left  + sixth;
        int e5 = right - sixth;
        int e3 = (left + right) >>> 1; // The midpoint
        int e4 = e3 + sixth;
        int e2 = e3 - sixth;

        // Sort these elements in place using a 5-element sorting network
        if (a[e1] > a[e2]) { double t = a[e1]; a[e1] = a[e2]; a[e2] = t; }
        if (a[e4] > a[e5]) { double t = a[e4]; a[e4] = a[e5]; a[e5] = t; }
        if (a[e1] > a[e3]) { double t = a[e1]; a[e1] = a[e3]; a[e3] = t; }
        if (a[e2] > a[e3]) { double t = a[e2]; a[e2] = a[e3]; a[e3] = t; }
        if (a[e1] > a[e4]) { double t = a[e1]; a[e1] = a[e4]; a[e4] = t; }
        if (a[e3] > a[e4]) { double t = a[e3]; a[e3] = a[e4]; a[e4] = t; }
        if (a[e2] > a[e5]) { double t = a[e2]; a[e2] = a[e5]; a[e5] = t; }
        if (a[e2] > a[e3]) { double t = a[e2]; a[e2] = a[e3]; a[e3] = t; }
        if (a[e4] > a[e5]) { double t = a[e4]; a[e4] = a[e5]; a[e5] = t; }

        /*
         * Use the second and fourth of the five sorted elements as pivots.
         * These values are inexpensive approximations of the first and
         * second terciles of the array. Note that pivot1 <= pivot2.
         *
         * The pivots are stored in local variables, and the first and
         * the last of the sorted elements are moved to the locations
         * formerly occupied by the pivots. When partitioning is complete,
         * the pivots are swapped back into their final positions, and
         * excluded from subsequent sorting.
         */
        double pivot1 = a[e2]; a[e2] = a[left];
        double pivot2 = a[e4]; a[e4] = a[right];

        /*
         * Partitioning
         *
         *   left part         center part                  right part
         * ------------------------------------------------------------
         * [ < pivot1  |  pivot1 <= && <= pivot2  |   ?   |  > pivot2 ]
         * ------------------------------------------------------------
         *              ^                          ^     ^
         *              |                          |     |
         *             less                        k   great
         */

        // Pointers
        int less  = left  + 1; // The index of first element of center part
        int great = right - 1; // The index before first element of right part

        boolean pivotsDiffer = pivot1 != pivot2;

        if (pivotsDiffer) {
            /*
             * Invariants:
             *              all in (left, less)   < pivot1
             *    pivot1 <= all in [less, k)     <= pivot2
             *              all in (great, right) > pivot2
             *
             * Pointer k is the first index of ?-part
             */
            for (int k = less; k <= great; k++) {
                double ak = a[k];

                if (ak < pivot1) {
                    a[k] = a[less];
                    a[less++] = ak;
                } else if (ak > pivot2) {
                    while (a[great] > pivot2 && k < great) {
                        great--;
                    }
                    a[k] = a[great];
                    a[great--] = ak;
                    ak = a[k];

                    if (ak < pivot1) {
                        a[k] = a[less];
                        a[less++] = ak;
                    }
                }
            }
        } else { // Pivots are equal
            /*
             * Partition degenerates to the traditional 3-way
             * (or "Dutch National Flag") partition:
             *
             *   left part   center part            right part
             * -------------------------------------------------
             * [  < pivot  |  == pivot  |    ?    |  > pivot   ]
             * -------------------------------------------------
             *
             *              ^            ^       ^
             *              |            |       |
             *             less          k     great
             *
             * Invariants:
             *
             *   all in (left, less)   < pivot
             *   all in [less, k)     == pivot
             *   all in (great, right) > pivot
             *
             * Pointer k is the first index of ?-part
             */
            for (int k = less; k <= great; k++) {
                double ak = a[k];

                if (ak == pivot1) {
                  continue;
                }
                if (ak < pivot1) {
                    a[k] = a[less];
                    a[less++] = ak;
                } else {
                    while (a[great] > pivot1) {
                        great--;
                    }
                    a[k] = a[great];
                    a[great--] = ak;
                    ak = a[k];

                    if (ak < pivot1) {
                        a[k] = a[less];
                        a[less++] = ak;
                    }
                }
            }
        }

        // Swap pivots into their final positions
        a[left]  = a[less  - 1]; a[less  - 1] = pivot1;
        a[right] = a[great + 1]; a[great + 1] = pivot2;

        // Sort left and right parts recursively, excluding known pivot values
A
alanb 已提交
1918 1919
        doSort(a, left,   less - 2);
        doSort(a, great + 2, right);
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954

        /*
         * If pivot1 == pivot2, all elements from center
         * part are equal and, therefore, already sorted
         */
        if (!pivotsDiffer) {
            return;
        }

        /*
         * If center part is too large (comprises > 5/6 of
         * the array), swap internal pivot values to ends
         */
        if (less < e1 && e5 < great) {
            while (a[less] == pivot1) {
                less++;
            }
            for (int k = less + 1; k <= great; k++) {
                if (a[k] == pivot1) {
                    a[k] = a[less];
                    a[less++] = pivot1;
                }
            }
            while (a[great] == pivot2) {
                great--;
            }
            for (int k = great - 1; k >= less; k--) {
                if (a[k] == pivot2) {
                    a[k] = a[great];
                    a[great--] = pivot2;
                }
            }
        }

        // Sort center part recursively, excluding known pivot values
A
alanb 已提交
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
        doSort(a, less, great);
    }

    /**
     * Checks that {@code fromIndex} and {@code toIndex} are in
     * the range and throws an appropriate exception, if they aren't.
     */
    private static void rangeCheck(int length, int fromIndex, int toIndex) {
        if (fromIndex > toIndex) {
            throw new IllegalArgumentException(
                "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
        }
        if (fromIndex < 0) {
            throw new ArrayIndexOutOfBoundsException(fromIndex);
        }
        if (toIndex > length) {
            throw new ArrayIndexOutOfBoundsException(toIndex);
        }
1973 1974
    }
}