diff --git a/src/java.base/share/classes/java/util/DualPivotQuicksort.java b/src/java.base/share/classes/java/util/DualPivotQuicksort.java index 3dcc7fee1f525..31ddc66e23607 100644 --- a/src/java.base/share/classes/java/util/DualPivotQuicksort.java +++ b/src/java.base/share/classes/java/util/DualPivotQuicksort.java @@ -1,4164 +1,4567 @@ -/* - * Copyright (c) 2009, 2021, Oracle and/or its affiliates. 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. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.util; - -import java.util.concurrent.CountedCompleter; -import java.util.concurrent.RecursiveTask; - -/** - * This class implements powerful and fully optimized versions, both - * sequential and parallel, of the Dual-Pivot Quicksort algorithm by - * Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch. This algorithm - * offers O(n log(n)) performance on all data sets, and is typically - * faster than traditional (one-pivot) Quicksort implementations. - * - * There are also additional algorithms, invoked from the Dual-Pivot - * Quicksort, such as mixed insertion sort, merging of runs and heap - * sort, counting sort and parallel merge sort. - * - * @author Vladimir Yaroslavskiy - * @author Jon Bentley - * @author Josh Bloch - * @author Doug Lea - * - * @version 2018.08.18 - * - * @since 1.7 * 14 - */ -final class DualPivotQuicksort { - - /** - * Prevents instantiation. - */ - private DualPivotQuicksort() {} - - /** - * Max array size to use mixed insertion sort. - */ - private static final int MAX_MIXED_INSERTION_SORT_SIZE = 65; - - /** - * Max array size to use insertion sort. - */ - private static final int MAX_INSERTION_SORT_SIZE = 44; - - /** - * Min array size to perform sorting in parallel. - */ - private static final int MIN_PARALLEL_SORT_SIZE = 4 << 10; - - /** - * Min array size to try merging of runs. - */ - private static final int MIN_TRY_MERGE_SIZE = 4 << 10; - - /** - * Min size of the first run to continue with scanning. - */ - private static final int MIN_FIRST_RUN_SIZE = 16; - - /** - * Min factor for the first runs to continue scanning. - */ - private static final int MIN_FIRST_RUNS_FACTOR = 7; - - /** - * Max capacity of the index array for tracking runs. - */ - private static final int MAX_RUN_CAPACITY = 5 << 10; - - /** - * Min number of runs, required by parallel merging. - */ - private static final int MIN_RUN_COUNT = 4; - - /** - * Min array size to use parallel merging of parts. - */ - private static final int MIN_PARALLEL_MERGE_PARTS_SIZE = 4 << 10; - - /** - * Min size of a byte array to use counting sort. - */ - private static final int MIN_BYTE_COUNTING_SORT_SIZE = 64; - - /** - * Min size of a short or char array to use counting sort. - */ - private static final int MIN_SHORT_OR_CHAR_COUNTING_SORT_SIZE = 1750; - - /** - * Threshold of mixed insertion sort is incremented by this value. - */ - private static final int DELTA = 3 << 1; - - /** - * Max recursive partitioning depth before using heap sort. - */ - private static final int MAX_RECURSION_DEPTH = 64 * DELTA; - - /** - * Calculates the double depth of parallel merging. - * Depth is negative, if tasks split before sorting. - * - * @param parallelism the parallelism level - * @param size the target size - * @return the depth of parallel merging - */ - private static int getDepth(int parallelism, int size) { - int depth = 0; - - while ((parallelism >>= 3) > 0 && (size >>= 2) > 0) { - depth -= 2; - } - return depth; - } - - /** - * Sorts the specified range of the array using parallel merge - * sort and/or Dual-Pivot Quicksort. - * - * To balance the faster splitting and parallelism of merge sort - * with the faster element partitioning of Quicksort, ranges are - * subdivided in tiers such that, if there is enough parallelism, - * the four-way parallel merge is started, still ensuring enough - * parallelism to process the partitions. - * - * @param a the array to be sorted - * @param parallelism the parallelism level - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - static void sort(int[] a, int parallelism, int low, int high) { - int size = high - low; - - if (parallelism > 1 && size > MIN_PARALLEL_SORT_SIZE) { - int depth = getDepth(parallelism, size >> 12); - int[] b = depth == 0 ? null : new int[size]; - new Sorter(null, a, b, low, size, low, depth).invoke(); - } else { - sort(null, a, 0, low, high); - } - } - - /** - * Sorts the specified array using the Dual-Pivot Quicksort and/or - * other sorts in special-cases, possibly with parallel partitions. - * - * @param sorter parallel context - * @param a the array to be sorted - * @param bits the combination of recursion depth and bit flag, where - * the right bit "0" indicates that array is the leftmost part - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - static void sort(Sorter sorter, int[] a, int bits, int low, int high) { - while (true) { - int end = high - 1, size = high - low; - - /* - * Run mixed insertion sort on small non-leftmost parts. - */ - if (size < MAX_MIXED_INSERTION_SORT_SIZE + bits && (bits & 1) > 0) { - mixedInsertionSort(a, low, high - 3 * ((size >> 5) << 3), high); - return; - } - - /* - * Invoke insertion sort on small leftmost part. - */ - if (size < MAX_INSERTION_SORT_SIZE) { - insertionSort(a, low, high); - return; - } - - /* - * Check if the whole array or large non-leftmost - * parts are nearly sorted and then merge runs. - */ - if ((bits == 0 || size > MIN_TRY_MERGE_SIZE && (bits & 1) > 0) - && tryMergeRuns(sorter, a, low, size)) { - return; - } - - /* - * Switch to heap sort if execution - * time is becoming quadratic. - */ - if ((bits += DELTA) > MAX_RECURSION_DEPTH) { - heapSort(a, low, high); - return; - } - - /* - * Use an inexpensive approximation of the golden ratio - * to select five sample elements and determine pivots. - */ - int step = (size >> 3) * 3 + 3; - - /* - * Five elements around (and including) the central element - * will be used for pivot selection as described below. The - * unequal choice of spacing these elements was empirically - * determined to work well on a wide variety of inputs. - */ - int e1 = low + step; - int e5 = end - step; - int e3 = (e1 + e5) >>> 1; - int e2 = (e1 + e3) >>> 1; - int e4 = (e3 + e5) >>> 1; - int a3 = a[e3]; - - /* - * Sort these elements in place by the combination - * of 4-element sorting network and insertion sort. - * - * 5 ------o-----------o------------ - * | | - * 4 ------|-----o-----o-----o------ - * | | | - * 2 ------o-----|-----o-----o------ - * | | - * 1 ------------o-----o------------ - */ - if (a[e5] < a[e2]) { int t = a[e5]; a[e5] = a[e2]; a[e2] = t; } - if (a[e4] < a[e1]) { int t = a[e4]; a[e4] = a[e1]; a[e1] = t; } - if (a[e5] < a[e4]) { int t = a[e5]; a[e5] = a[e4]; a[e4] = t; } - if (a[e2] < a[e1]) { int t = a[e2]; a[e2] = a[e1]; a[e1] = t; } - if (a[e4] < a[e2]) { int t = a[e4]; a[e4] = a[e2]; a[e2] = t; } - - if (a3 < a[e2]) { - if (a3 < a[e1]) { - a[e3] = a[e2]; a[e2] = a[e1]; a[e1] = a3; - } else { - a[e3] = a[e2]; a[e2] = a3; - } - } else if (a3 > a[e4]) { - if (a3 > a[e5]) { - a[e3] = a[e4]; a[e4] = a[e5]; a[e5] = a3; - } else { - a[e3] = a[e4]; a[e4] = a3; - } - } - - // Pointers - int lower = low; // The index of the last element of the left part - int upper = end; // The index of the first element of the right part - - /* - * Partitioning with 2 pivots in case of different elements. - */ - if (a[e1] < a[e2] && a[e2] < a[e3] && a[e3] < a[e4] && a[e4] < a[e5]) { - - /* - * Use the first and fifth of the five sorted elements as - * the pivots. These values are inexpensive approximation - * of tertiles. Note, that pivot1 < pivot2. - */ - int pivot1 = a[e1]; - int pivot2 = a[e5]; - - /* - * The first and the last elements to be sorted are moved - * to the locations formerly occupied by the pivots. When - * partitioning is completed, the pivots are swapped back - * into their final positions, and excluded from the next - * subsequent sorting. - */ - a[e1] = a[lower]; - a[e5] = a[upper]; - - /* - * Skip elements, which are less or greater than the pivots. - */ - while (a[++lower] < pivot1); - while (a[--upper] > pivot2); - - /* - * Backward 3-interval partitioning - * - * left part central part right part - * +------------------------------------------------------------+ - * | < pivot1 | ? | pivot1 <= && <= pivot2 | > pivot2 | - * +------------------------------------------------------------+ - * ^ ^ ^ - * | | | - * lower k upper - * - * Invariants: - * - * all in (low, lower] < pivot1 - * pivot1 <= all in (k, upper) <= pivot2 - * all in [upper, end) > pivot2 - * - * Pointer k is the last index of ?-part - */ - for (int unused = --lower, k = ++upper; --k > lower; ) { - int ak = a[k]; - - if (ak < pivot1) { // Move a[k] to the left side - while (lower < k) { - if (a[++lower] >= pivot1) { - if (a[lower] > pivot2) { - a[k] = a[--upper]; - a[upper] = a[lower]; - } else { - a[k] = a[lower]; - } - a[lower] = ak; - break; - } - } - } else if (ak > pivot2) { // Move a[k] to the right side - a[k] = a[--upper]; - a[upper] = ak; - } - } - - /* - * Swap the pivots into their final positions. - */ - a[low] = a[lower]; a[lower] = pivot1; - a[end] = a[upper]; a[upper] = pivot2; - - /* - * Sort non-left parts recursively (possibly in parallel), - * excluding known pivots. - */ - if (size > MIN_PARALLEL_SORT_SIZE && sorter != null) { - sorter.forkSorter(bits | 1, lower + 1, upper); - sorter.forkSorter(bits | 1, upper + 1, high); - } else { - sort(sorter, a, bits | 1, lower + 1, upper); - sort(sorter, a, bits | 1, upper + 1, high); - } - - } else { // Use single pivot in case of many equal elements - - /* - * Use the third of the five sorted elements as the pivot. - * This value is inexpensive approximation of the median. - */ - int pivot = a[e3]; - - /* - * The first element to be sorted is moved to the - * location formerly occupied by the pivot. After - * completion of partitioning the pivot is swapped - * back into its final position, and excluded from - * the next subsequent sorting. - */ - a[e3] = a[lower]; - - /* - * Traditional 3-way (Dutch National Flag) partitioning - * - * left part central part right part - * +------------------------------------------------------+ - * | < pivot | ? | == pivot | > pivot | - * +------------------------------------------------------+ - * ^ ^ ^ - * | | | - * lower k upper - * - * Invariants: - * - * all in (low, lower] < pivot - * all in (k, upper) == pivot - * all in [upper, end] > pivot - * - * Pointer k is the last index of ?-part - */ - for (int k = ++upper; --k > lower; ) { - int ak = a[k]; - - if (ak != pivot) { - a[k] = pivot; - - if (ak < pivot) { // Move a[k] to the left side - while (a[++lower] < pivot); - - if (a[lower] > pivot) { - a[--upper] = a[lower]; - } - a[lower] = ak; - } else { // ak > pivot - Move a[k] to the right side - a[--upper] = ak; - } - } - } - - /* - * Swap the pivot into its final position. - */ - a[low] = a[lower]; a[lower] = pivot; - - /* - * Sort the right part (possibly in parallel), excluding - * known pivot. All elements from the central part are - * equal and therefore already sorted. - */ - if (size > MIN_PARALLEL_SORT_SIZE && sorter != null) { - sorter.forkSorter(bits | 1, upper, high); - } else { - sort(sorter, a, bits | 1, upper, high); - } - } - high = lower; // Iterate along the left part - } - } - - /** - * Sorts the specified range of the array using mixed insertion sort. - * - * Mixed insertion sort is combination of simple insertion sort, - * pin insertion sort and pair insertion sort. - * - * In the context of Dual-Pivot Quicksort, the pivot element - * from the left part plays the role of sentinel, because it - * is less than any elements from the given part. Therefore, - * expensive check of the left range can be skipped on each - * iteration unless it is the leftmost call. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param end the index of the last element for simple insertion sort - * @param high the index of the last element, exclusive, to be sorted - */ - private static void mixedInsertionSort(int[] a, int low, int end, int high) { - if (end == high) { - - /* - * Invoke simple insertion sort on tiny array. - */ - for (int i; ++low < end; ) { - int ai = a[i = low]; - - while (ai < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - } - } else { - - /* - * Start with pin insertion sort on small part. - * - * Pin insertion sort is extended simple insertion sort. - * The main idea of this sort is to put elements larger - * than an element called pin to the end of array (the - * proper area for such elements). It avoids expensive - * movements of these elements through the whole array. - */ - int pin = a[end]; - - for (int i, p = high; ++low < end; ) { - int ai = a[i = low]; - - if (ai < a[i - 1]) { // Small element - - /* - * Insert small element into sorted part. - */ - a[i] = a[--i]; - - while (ai < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - - } else if (p > i && ai > pin) { // Large element - - /* - * Find element smaller than pin. - */ - while (a[--p] > pin); - - /* - * Swap it with large element. - */ - if (p > i) { - ai = a[p]; - a[p] = a[i]; - } - - /* - * Insert small element into sorted part. - */ - while (ai < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - } - } - - /* - * Continue with pair insertion sort on remain part. - */ - for (int i; low < high; ++low) { - int a1 = a[i = low], a2 = a[++low]; - - /* - * Insert two elements per iteration: at first, insert the - * larger element and then insert the smaller element, but - * from the position where the larger element was inserted. - */ - if (a1 > a2) { - - while (a1 < a[--i]) { - a[i + 2] = a[i]; - } - a[++i + 1] = a1; - - while (a2 < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = a2; - - } else if (a1 < a[i - 1]) { - - while (a2 < a[--i]) { - a[i + 2] = a[i]; - } - a[++i + 1] = a2; - - while (a1 < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = a1; - } - } - } - } - - /** - * Sorts the specified range of the array using insertion sort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void insertionSort(int[] a, int low, int high) { - for (int i, k = low; ++k < high; ) { - int ai = a[i = k]; - - if (ai < a[i - 1]) { - while (--i >= low && ai < a[i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - } - } - } - - /** - * Sorts the specified range of the array using heap sort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void heapSort(int[] a, int low, int high) { - for (int k = (low + high) >>> 1; k > low; ) { - pushDown(a, --k, a[k], low, high); - } - while (--high > low) { - int max = a[low]; - pushDown(a, low, a[high], low, high); - a[high] = max; - } - } - - /** - * Pushes specified element down during heap sort. - * - * @param a the given array - * @param p the start index - * @param value the given element - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void pushDown(int[] a, int p, int value, int low, int high) { - for (int k ;; a[p] = a[p = k]) { - k = (p << 1) - low + 2; // Index of the right child - - if (k > high) { - break; - } - if (k == high || a[k] < a[k - 1]) { - --k; - } - if (a[k] <= value) { - break; - } - } - a[p] = value; - } - - /** - * Tries to sort the specified range of the array. - * - * @param sorter parallel context - * @param a the array to be sorted - * @param low the index of the first element to be sorted - * @param size the array size - * @return true if finally sorted, false otherwise - */ - private static boolean tryMergeRuns(Sorter sorter, int[] a, int low, int size) { - - /* - * The run array is constructed only if initial runs are - * long enough to continue, run[i] then holds start index - * of the i-th sequence of elements in non-descending order. - */ - int[] run = null; - int high = low + size; - int count = 1, last = low; - - /* - * Identify all possible runs. - */ - for (int k = low + 1; k < high; ) { - - /* - * Find the end index of the current run. - */ - if (a[k - 1] < a[k]) { - - // Identify ascending sequence - while (++k < high && a[k - 1] <= a[k]); - - } else if (a[k - 1] > a[k]) { - - // Identify descending sequence - while (++k < high && a[k - 1] >= a[k]); - - // Reverse into ascending order - for (int i = last - 1, j = k; ++i < --j && a[i] > a[j]; ) { - int ai = a[i]; a[i] = a[j]; a[j] = ai; - } - } else { // Identify constant sequence - for (int ak = a[k]; ++k < high && ak == a[k]; ); - - if (k < high) { - continue; - } - } - - /* - * Check special cases. - */ - if (run == null) { - if (k == high) { - - /* - * The array is monotonous sequence, - * and therefore already sorted. - */ - return true; - } - - if (k - low < MIN_FIRST_RUN_SIZE) { - - /* - * The first run is too small - * to proceed with scanning. - */ - return false; - } - - run = new int[((size >> 10) | 0x7F) & 0x3FF]; - run[0] = low; - - } else if (a[last - 1] > a[last]) { - - if (count > (k - low) >> MIN_FIRST_RUNS_FACTOR) { - - /* - * The first runs are not long - * enough to continue scanning. - */ - return false; - } - - if (++count == MAX_RUN_CAPACITY) { - - /* - * Array is not highly structured. - */ - return false; - } - - if (count == run.length) { - - /* - * Increase capacity of index array. - */ - run = Arrays.copyOf(run, count << 1); - } - } - run[count] = (last = k); - } - - /* - * Merge runs of highly structured array. - */ - if (count > 1) { - int[] b; int offset = low; - - if (sorter == null || (b = (int[]) sorter.b) == null) { - b = new int[size]; - } else { - offset = sorter.offset; - } - mergeRuns(a, b, offset, 1, sorter != null, run, 0, count); - } - return true; - } - - /** - * Merges the specified runs. - * - * @param a the source array - * @param b the temporary buffer used in merging - * @param offset the start index in the source, inclusive - * @param aim specifies merging: to source ( > 0), buffer ( < 0) or any ( == 0) - * @param parallel indicates whether merging is performed in parallel - * @param run the start indexes of the runs, inclusive - * @param lo the start index of the first run, inclusive - * @param hi the start index of the last run, inclusive - * @return the destination where runs are merged - */ - private static int[] mergeRuns(int[] a, int[] b, int offset, - int aim, boolean parallel, int[] run, int lo, int hi) { - - if (hi - lo == 1) { - if (aim >= 0) { - return a; - } - for (int i = run[hi], j = i - offset, low = run[lo]; i > low; - b[--j] = a[--i] - ); - return b; - } - - /* - * Split into approximately equal parts. - */ - int mi = lo, rmi = (run[lo] + run[hi]) >>> 1; - while (run[++mi + 1] <= rmi); - - /* - * Merge the left and right parts. - */ - int[] a1, a2; - - if (parallel && hi - lo > MIN_RUN_COUNT) { - RunMerger merger = new RunMerger(a, b, offset, 0, run, mi, hi).forkMe(); - a1 = mergeRuns(a, b, offset, -aim, true, run, lo, mi); - a2 = (int[]) merger.getDestination(); - } else { - a1 = mergeRuns(a, b, offset, -aim, false, run, lo, mi); - a2 = mergeRuns(a, b, offset, 0, false, run, mi, hi); - } - - int[] dst = a1 == a ? b : a; - - int k = a1 == a ? run[lo] - offset : run[lo]; - int lo1 = a1 == b ? run[lo] - offset : run[lo]; - int hi1 = a1 == b ? run[mi] - offset : run[mi]; - int lo2 = a2 == b ? run[mi] - offset : run[mi]; - int hi2 = a2 == b ? run[hi] - offset : run[hi]; - - if (parallel) { - new Merger(null, dst, k, a1, lo1, hi1, a2, lo2, hi2).invoke(); - } else { - mergeParts(null, dst, k, a1, lo1, hi1, a2, lo2, hi2); - } - return dst; - } - - /** - * Merges the sorted parts. - * - * @param merger parallel context - * @param dst the destination where parts are merged - * @param k the start index of the destination, inclusive - * @param a1 the first part - * @param lo1 the start index of the first part, inclusive - * @param hi1 the end index of the first part, exclusive - * @param a2 the second part - * @param lo2 the start index of the second part, inclusive - * @param hi2 the end index of the second part, exclusive - */ - private static void mergeParts(Merger merger, int[] dst, int k, - int[] a1, int lo1, int hi1, int[] a2, int lo2, int hi2) { - - if (merger != null && a1 == a2) { - - while (true) { - - /* - * The first part must be larger. - */ - if (hi1 - lo1 < hi2 - lo2) { - int lo = lo1; lo1 = lo2; lo2 = lo; - int hi = hi1; hi1 = hi2; hi2 = hi; - } - - /* - * Small parts will be merged sequentially. - */ - if (hi1 - lo1 < MIN_PARALLEL_MERGE_PARTS_SIZE) { - break; - } - - /* - * Find the median of the larger part. - */ - int mi1 = (lo1 + hi1) >>> 1; - int key = a1[mi1]; - int mi2 = hi2; - - /* - * Partition the smaller part. - */ - for (int loo = lo2; loo < mi2; ) { - int t = (loo + mi2) >>> 1; - - if (key > a2[t]) { - loo = t + 1; - } else { - mi2 = t; - } - } - - int d = mi2 - lo2 + mi1 - lo1; - - /* - * Merge the right sub-parts in parallel. - */ - merger.forkMerger(dst, k + d, a1, mi1, hi1, a2, mi2, hi2); - - /* - * Process the sub-left parts. - */ - hi1 = mi1; - hi2 = mi2; - } - } - - /* - * Merge small parts sequentially. - */ - while (lo1 < hi1 && lo2 < hi2) { - dst[k++] = a1[lo1] < a2[lo2] ? a1[lo1++] : a2[lo2++]; - } - if (dst != a1 || k < lo1) { - while (lo1 < hi1) { - dst[k++] = a1[lo1++]; - } - } - if (dst != a2 || k < lo2) { - while (lo2 < hi2) { - dst[k++] = a2[lo2++]; - } - } - } - -// [long] - - /** - * Sorts the specified range of the array using parallel merge - * sort and/or Dual-Pivot Quicksort. - * - * To balance the faster splitting and parallelism of merge sort - * with the faster element partitioning of Quicksort, ranges are - * subdivided in tiers such that, if there is enough parallelism, - * the four-way parallel merge is started, still ensuring enough - * parallelism to process the partitions. - * - * @param a the array to be sorted - * @param parallelism the parallelism level - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - static void sort(long[] a, int parallelism, int low, int high) { - int size = high - low; - - if (parallelism > 1 && size > MIN_PARALLEL_SORT_SIZE) { - int depth = getDepth(parallelism, size >> 12); - long[] b = depth == 0 ? null : new long[size]; - new Sorter(null, a, b, low, size, low, depth).invoke(); - } else { - sort(null, a, 0, low, high); - } - } - - /** - * Sorts the specified array using the Dual-Pivot Quicksort and/or - * other sorts in special-cases, possibly with parallel partitions. - * - * @param sorter parallel context - * @param a the array to be sorted - * @param bits the combination of recursion depth and bit flag, where - * the right bit "0" indicates that array is the leftmost part - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - static void sort(Sorter sorter, long[] a, int bits, int low, int high) { - while (true) { - int end = high - 1, size = high - low; - - /* - * Run mixed insertion sort on small non-leftmost parts. - */ - if (size < MAX_MIXED_INSERTION_SORT_SIZE + bits && (bits & 1) > 0) { - mixedInsertionSort(a, low, high - 3 * ((size >> 5) << 3), high); - return; - } - - /* - * Invoke insertion sort on small leftmost part. - */ - if (size < MAX_INSERTION_SORT_SIZE) { - insertionSort(a, low, high); - return; - } - - /* - * Check if the whole array or large non-leftmost - * parts are nearly sorted and then merge runs. - */ - if ((bits == 0 || size > MIN_TRY_MERGE_SIZE && (bits & 1) > 0) - && tryMergeRuns(sorter, a, low, size)) { - return; - } - - /* - * Switch to heap sort if execution - * time is becoming quadratic. - */ - if ((bits += DELTA) > MAX_RECURSION_DEPTH) { - heapSort(a, low, high); - return; - } - - /* - * Use an inexpensive approximation of the golden ratio - * to select five sample elements and determine pivots. - */ - int step = (size >> 3) * 3 + 3; - - /* - * Five elements around (and including) the central element - * will be used for pivot selection as described below. The - * unequal choice of spacing these elements was empirically - * determined to work well on a wide variety of inputs. - */ - int e1 = low + step; - int e5 = end - step; - int e3 = (e1 + e5) >>> 1; - int e2 = (e1 + e3) >>> 1; - int e4 = (e3 + e5) >>> 1; - long a3 = a[e3]; - - /* - * Sort these elements in place by the combination - * of 4-element sorting network and insertion sort. - * - * 5 ------o-----------o------------ - * | | - * 4 ------|-----o-----o-----o------ - * | | | - * 2 ------o-----|-----o-----o------ - * | | - * 1 ------------o-----o------------ - */ - if (a[e5] < a[e2]) { long t = a[e5]; a[e5] = a[e2]; a[e2] = t; } - if (a[e4] < a[e1]) { long t = a[e4]; a[e4] = a[e1]; a[e1] = t; } - if (a[e5] < a[e4]) { long t = a[e5]; a[e5] = a[e4]; a[e4] = t; } - if (a[e2] < a[e1]) { long t = a[e2]; a[e2] = a[e1]; a[e1] = t; } - if (a[e4] < a[e2]) { long t = a[e4]; a[e4] = a[e2]; a[e2] = t; } - - if (a3 < a[e2]) { - if (a3 < a[e1]) { - a[e3] = a[e2]; a[e2] = a[e1]; a[e1] = a3; - } else { - a[e3] = a[e2]; a[e2] = a3; - } - } else if (a3 > a[e4]) { - if (a3 > a[e5]) { - a[e3] = a[e4]; a[e4] = a[e5]; a[e5] = a3; - } else { - a[e3] = a[e4]; a[e4] = a3; - } - } - - // Pointers - int lower = low; // The index of the last element of the left part - int upper = end; // The index of the first element of the right part - - /* - * Partitioning with 2 pivots in case of different elements. - */ - if (a[e1] < a[e2] && a[e2] < a[e3] && a[e3] < a[e4] && a[e4] < a[e5]) { - - /* - * Use the first and fifth of the five sorted elements as - * the pivots. These values are inexpensive approximation - * of tertiles. Note, that pivot1 < pivot2. - */ - long pivot1 = a[e1]; - long pivot2 = a[e5]; - - /* - * The first and the last elements to be sorted are moved - * to the locations formerly occupied by the pivots. When - * partitioning is completed, the pivots are swapped back - * into their final positions, and excluded from the next - * subsequent sorting. - */ - a[e1] = a[lower]; - a[e5] = a[upper]; - - /* - * Skip elements, which are less or greater than the pivots. - */ - while (a[++lower] < pivot1); - while (a[--upper] > pivot2); - - /* - * Backward 3-interval partitioning - * - * left part central part right part - * +------------------------------------------------------------+ - * | < pivot1 | ? | pivot1 <= && <= pivot2 | > pivot2 | - * +------------------------------------------------------------+ - * ^ ^ ^ - * | | | - * lower k upper - * - * Invariants: - * - * all in (low, lower] < pivot1 - * pivot1 <= all in (k, upper) <= pivot2 - * all in [upper, end) > pivot2 - * - * Pointer k is the last index of ?-part - */ - for (int unused = --lower, k = ++upper; --k > lower; ) { - long ak = a[k]; - - if (ak < pivot1) { // Move a[k] to the left side - while (lower < k) { - if (a[++lower] >= pivot1) { - if (a[lower] > pivot2) { - a[k] = a[--upper]; - a[upper] = a[lower]; - } else { - a[k] = a[lower]; - } - a[lower] = ak; - break; - } - } - } else if (ak > pivot2) { // Move a[k] to the right side - a[k] = a[--upper]; - a[upper] = ak; - } - } - - /* - * Swap the pivots into their final positions. - */ - a[low] = a[lower]; a[lower] = pivot1; - a[end] = a[upper]; a[upper] = pivot2; - - /* - * Sort non-left parts recursively (possibly in parallel), - * excluding known pivots. - */ - if (size > MIN_PARALLEL_SORT_SIZE && sorter != null) { - sorter.forkSorter(bits | 1, lower + 1, upper); - sorter.forkSorter(bits | 1, upper + 1, high); - } else { - sort(sorter, a, bits | 1, lower + 1, upper); - sort(sorter, a, bits | 1, upper + 1, high); - } - - } else { // Use single pivot in case of many equal elements - - /* - * Use the third of the five sorted elements as the pivot. - * This value is inexpensive approximation of the median. - */ - long pivot = a[e3]; - - /* - * The first element to be sorted is moved to the - * location formerly occupied by the pivot. After - * completion of partitioning the pivot is swapped - * back into its final position, and excluded from - * the next subsequent sorting. - */ - a[e3] = a[lower]; - - /* - * Traditional 3-way (Dutch National Flag) partitioning - * - * left part central part right part - * +------------------------------------------------------+ - * | < pivot | ? | == pivot | > pivot | - * +------------------------------------------------------+ - * ^ ^ ^ - * | | | - * lower k upper - * - * Invariants: - * - * all in (low, lower] < pivot - * all in (k, upper) == pivot - * all in [upper, end] > pivot - * - * Pointer k is the last index of ?-part - */ - for (int k = ++upper; --k > lower; ) { - long ak = a[k]; - - if (ak != pivot) { - a[k] = pivot; - - if (ak < pivot) { // Move a[k] to the left side - while (a[++lower] < pivot); - - if (a[lower] > pivot) { - a[--upper] = a[lower]; - } - a[lower] = ak; - } else { // ak > pivot - Move a[k] to the right side - a[--upper] = ak; - } - } - } - - /* - * Swap the pivot into its final position. - */ - a[low] = a[lower]; a[lower] = pivot; - - /* - * Sort the right part (possibly in parallel), excluding - * known pivot. All elements from the central part are - * equal and therefore already sorted. - */ - if (size > MIN_PARALLEL_SORT_SIZE && sorter != null) { - sorter.forkSorter(bits | 1, upper, high); - } else { - sort(sorter, a, bits | 1, upper, high); - } - } - high = lower; // Iterate along the left part - } - } - - /** - * Sorts the specified range of the array using mixed insertion sort. - * - * Mixed insertion sort is combination of simple insertion sort, - * pin insertion sort and pair insertion sort. - * - * In the context of Dual-Pivot Quicksort, the pivot element - * from the left part plays the role of sentinel, because it - * is less than any elements from the given part. Therefore, - * expensive check of the left range can be skipped on each - * iteration unless it is the leftmost call. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param end the index of the last element for simple insertion sort - * @param high the index of the last element, exclusive, to be sorted - */ - private static void mixedInsertionSort(long[] a, int low, int end, int high) { - if (end == high) { - - /* - * Invoke simple insertion sort on tiny array. - */ - for (int i; ++low < end; ) { - long ai = a[i = low]; - - while (ai < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - } - } else { - - /* - * Start with pin insertion sort on small part. - * - * Pin insertion sort is extended simple insertion sort. - * The main idea of this sort is to put elements larger - * than an element called pin to the end of array (the - * proper area for such elements). It avoids expensive - * movements of these elements through the whole array. - */ - long pin = a[end]; - - for (int i, p = high; ++low < end; ) { - long ai = a[i = low]; - - if (ai < a[i - 1]) { // Small element - - /* - * Insert small element into sorted part. - */ - a[i] = a[--i]; - - while (ai < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - - } else if (p > i && ai > pin) { // Large element - - /* - * Find element smaller than pin. - */ - while (a[--p] > pin); - - /* - * Swap it with large element. - */ - if (p > i) { - ai = a[p]; - a[p] = a[i]; - } - - /* - * Insert small element into sorted part. - */ - while (ai < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - } - } - - /* - * Continue with pair insertion sort on remain part. - */ - for (int i; low < high; ++low) { - long a1 = a[i = low], a2 = a[++low]; - - /* - * Insert two elements per iteration: at first, insert the - * larger element and then insert the smaller element, but - * from the position where the larger element was inserted. - */ - if (a1 > a2) { - - while (a1 < a[--i]) { - a[i + 2] = a[i]; - } - a[++i + 1] = a1; - - while (a2 < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = a2; - - } else if (a1 < a[i - 1]) { - - while (a2 < a[--i]) { - a[i + 2] = a[i]; - } - a[++i + 1] = a2; - - while (a1 < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = a1; - } - } - } - } - - /** - * Sorts the specified range of the array using insertion sort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void insertionSort(long[] a, int low, int high) { - for (int i, k = low; ++k < high; ) { - long ai = a[i = k]; - - if (ai < a[i - 1]) { - while (--i >= low && ai < a[i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - } - } - } - - /** - * Sorts the specified range of the array using heap sort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void heapSort(long[] a, int low, int high) { - for (int k = (low + high) >>> 1; k > low; ) { - pushDown(a, --k, a[k], low, high); - } - while (--high > low) { - long max = a[low]; - pushDown(a, low, a[high], low, high); - a[high] = max; - } - } - - /** - * Pushes specified element down during heap sort. - * - * @param a the given array - * @param p the start index - * @param value the given element - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void pushDown(long[] a, int p, long value, int low, int high) { - for (int k ;; a[p] = a[p = k]) { - k = (p << 1) - low + 2; // Index of the right child - - if (k > high) { - break; - } - if (k == high || a[k] < a[k - 1]) { - --k; - } - if (a[k] <= value) { - break; - } - } - a[p] = value; - } - - /** - * Tries to sort the specified range of the array. - * - * @param sorter parallel context - * @param a the array to be sorted - * @param low the index of the first element to be sorted - * @param size the array size - * @return true if finally sorted, false otherwise - */ - private static boolean tryMergeRuns(Sorter sorter, long[] a, int low, int size) { - - /* - * The run array is constructed only if initial runs are - * long enough to continue, run[i] then holds start index - * of the i-th sequence of elements in non-descending order. - */ - int[] run = null; - int high = low + size; - int count = 1, last = low; - - /* - * Identify all possible runs. - */ - for (int k = low + 1; k < high; ) { - - /* - * Find the end index of the current run. - */ - if (a[k - 1] < a[k]) { - - // Identify ascending sequence - while (++k < high && a[k - 1] <= a[k]); - - } else if (a[k - 1] > a[k]) { - - // Identify descending sequence - while (++k < high && a[k - 1] >= a[k]); - - // Reverse into ascending order - for (int i = last - 1, j = k; ++i < --j && a[i] > a[j]; ) { - long ai = a[i]; a[i] = a[j]; a[j] = ai; - } - } else { // Identify constant sequence - for (long ak = a[k]; ++k < high && ak == a[k]; ); - - if (k < high) { - continue; - } - } - - /* - * Check special cases. - */ - if (run == null) { - if (k == high) { - - /* - * The array is monotonous sequence, - * and therefore already sorted. - */ - return true; - } - - if (k - low < MIN_FIRST_RUN_SIZE) { - - /* - * The first run is too small - * to proceed with scanning. - */ - return false; - } - - run = new int[((size >> 10) | 0x7F) & 0x3FF]; - run[0] = low; - - } else if (a[last - 1] > a[last]) { - - if (count > (k - low) >> MIN_FIRST_RUNS_FACTOR) { - - /* - * The first runs are not long - * enough to continue scanning. - */ - return false; - } - - if (++count == MAX_RUN_CAPACITY) { - - /* - * Array is not highly structured. - */ - return false; - } - - if (count == run.length) { - - /* - * Increase capacity of index array. - */ - run = Arrays.copyOf(run, count << 1); - } - } - run[count] = (last = k); - } - - /* - * Merge runs of highly structured array. - */ - if (count > 1) { - long[] b; int offset = low; - - if (sorter == null || (b = (long[]) sorter.b) == null) { - b = new long[size]; - } else { - offset = sorter.offset; - } - mergeRuns(a, b, offset, 1, sorter != null, run, 0, count); - } - return true; - } - - /** - * Merges the specified runs. - * - * @param a the source array - * @param b the temporary buffer used in merging - * @param offset the start index in the source, inclusive - * @param aim specifies merging: to source ( > 0), buffer ( < 0) or any ( == 0) - * @param parallel indicates whether merging is performed in parallel - * @param run the start indexes of the runs, inclusive - * @param lo the start index of the first run, inclusive - * @param hi the start index of the last run, inclusive - * @return the destination where runs are merged - */ - private static long[] mergeRuns(long[] a, long[] b, int offset, - int aim, boolean parallel, int[] run, int lo, int hi) { - - if (hi - lo == 1) { - if (aim >= 0) { - return a; - } - for (int i = run[hi], j = i - offset, low = run[lo]; i > low; - b[--j] = a[--i] - ); - return b; - } - - /* - * Split into approximately equal parts. - */ - int mi = lo, rmi = (run[lo] + run[hi]) >>> 1; - while (run[++mi + 1] <= rmi); - - /* - * Merge the left and right parts. - */ - long[] a1, a2; - - if (parallel && hi - lo > MIN_RUN_COUNT) { - RunMerger merger = new RunMerger(a, b, offset, 0, run, mi, hi).forkMe(); - a1 = mergeRuns(a, b, offset, -aim, true, run, lo, mi); - a2 = (long[]) merger.getDestination(); - } else { - a1 = mergeRuns(a, b, offset, -aim, false, run, lo, mi); - a2 = mergeRuns(a, b, offset, 0, false, run, mi, hi); - } - - long[] dst = a1 == a ? b : a; - - int k = a1 == a ? run[lo] - offset : run[lo]; - int lo1 = a1 == b ? run[lo] - offset : run[lo]; - int hi1 = a1 == b ? run[mi] - offset : run[mi]; - int lo2 = a2 == b ? run[mi] - offset : run[mi]; - int hi2 = a2 == b ? run[hi] - offset : run[hi]; - - if (parallel) { - new Merger(null, dst, k, a1, lo1, hi1, a2, lo2, hi2).invoke(); - } else { - mergeParts(null, dst, k, a1, lo1, hi1, a2, lo2, hi2); - } - return dst; - } - - /** - * Merges the sorted parts. - * - * @param merger parallel context - * @param dst the destination where parts are merged - * @param k the start index of the destination, inclusive - * @param a1 the first part - * @param lo1 the start index of the first part, inclusive - * @param hi1 the end index of the first part, exclusive - * @param a2 the second part - * @param lo2 the start index of the second part, inclusive - * @param hi2 the end index of the second part, exclusive - */ - private static void mergeParts(Merger merger, long[] dst, int k, - long[] a1, int lo1, int hi1, long[] a2, int lo2, int hi2) { - - if (merger != null && a1 == a2) { - - while (true) { - - /* - * The first part must be larger. - */ - if (hi1 - lo1 < hi2 - lo2) { - int lo = lo1; lo1 = lo2; lo2 = lo; - int hi = hi1; hi1 = hi2; hi2 = hi; - } - - /* - * Small parts will be merged sequentially. - */ - if (hi1 - lo1 < MIN_PARALLEL_MERGE_PARTS_SIZE) { - break; - } - - /* - * Find the median of the larger part. - */ - int mi1 = (lo1 + hi1) >>> 1; - long key = a1[mi1]; - int mi2 = hi2; - - /* - * Partition the smaller part. - */ - for (int loo = lo2; loo < mi2; ) { - int t = (loo + mi2) >>> 1; - - if (key > a2[t]) { - loo = t + 1; - } else { - mi2 = t; - } - } - - int d = mi2 - lo2 + mi1 - lo1; - - /* - * Merge the right sub-parts in parallel. - */ - merger.forkMerger(dst, k + d, a1, mi1, hi1, a2, mi2, hi2); - - /* - * Process the sub-left parts. - */ - hi1 = mi1; - hi2 = mi2; - } - } - - /* - * Merge small parts sequentially. - */ - while (lo1 < hi1 && lo2 < hi2) { - dst[k++] = a1[lo1] < a2[lo2] ? a1[lo1++] : a2[lo2++]; - } - if (dst != a1 || k < lo1) { - while (lo1 < hi1) { - dst[k++] = a1[lo1++]; - } - } - if (dst != a2 || k < lo2) { - while (lo2 < hi2) { - dst[k++] = a2[lo2++]; - } - } - } - -// [byte] - - /** - * Sorts the specified range of the array using - * counting sort or insertion sort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - static void sort(byte[] a, int low, int high) { - if (high - low > MIN_BYTE_COUNTING_SORT_SIZE) { - countingSort(a, low, high); - } else { - insertionSort(a, low, high); - } - } - - /** - * Sorts the specified range of the array using insertion sort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void insertionSort(byte[] a, int low, int high) { - for (int i, k = low; ++k < high; ) { - byte ai = a[i = k]; - - if (ai < a[i - 1]) { - while (--i >= low && ai < a[i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - } - } - } - - /** - * The number of distinct byte values. - */ - private static final int NUM_BYTE_VALUES = 1 << 8; - - /** - * Max index of byte counter. - */ - private static final int MAX_BYTE_INDEX = Byte.MAX_VALUE + NUM_BYTE_VALUES + 1; - - /** - * Sorts the specified range of the array using counting sort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void countingSort(byte[] a, int low, int high) { - int[] count = new int[NUM_BYTE_VALUES]; - - /* - * Compute a histogram with the number of each values. - */ - for (int i = high; i > low; ++count[a[--i] & 0xFF]); - - /* - * Place values on their final positions. - */ - if (high - low > NUM_BYTE_VALUES) { - for (int i = MAX_BYTE_INDEX; --i > Byte.MAX_VALUE; ) { - int value = i & 0xFF; - - for (low = high - count[value]; high > low; - a[--high] = (byte) value - ); - } - } else { - for (int i = MAX_BYTE_INDEX; high > low; ) { - while (count[--i & 0xFF] == 0); - - int value = i & 0xFF; - int c = count[value]; - - do { - a[--high] = (byte) value; - } while (--c > 0); - } - } - } - -// [char] - - /** - * Sorts the specified range of the array using - * counting sort or Dual-Pivot Quicksort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - static void sort(char[] a, int low, int high) { - if (high - low > MIN_SHORT_OR_CHAR_COUNTING_SORT_SIZE) { - countingSort(a, low, high); - } else { - sort(a, 0, low, high); - } - } - - /** - * Sorts the specified array using the Dual-Pivot Quicksort and/or - * other sorts in special-cases, possibly with parallel partitions. - * - * @param a the array to be sorted - * @param bits the combination of recursion depth and bit flag, where - * the right bit "0" indicates that array is the leftmost part - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - static void sort(char[] a, int bits, int low, int high) { - while (true) { - int end = high - 1, size = high - low; - - /* - * Invoke insertion sort on small leftmost part. - */ - if (size < MAX_INSERTION_SORT_SIZE) { - insertionSort(a, low, high); - return; - } - - /* - * Switch to counting sort if execution - * time is becoming quadratic. - */ - if ((bits += DELTA) > MAX_RECURSION_DEPTH) { - countingSort(a, low, high); - return; - } - - /* - * Use an inexpensive approximation of the golden ratio - * to select five sample elements and determine pivots. - */ - int step = (size >> 3) * 3 + 3; - - /* - * Five elements around (and including) the central element - * will be used for pivot selection as described below. The - * unequal choice of spacing these elements was empirically - * determined to work well on a wide variety of inputs. - */ - int e1 = low + step; - int e5 = end - step; - int e3 = (e1 + e5) >>> 1; - int e2 = (e1 + e3) >>> 1; - int e4 = (e3 + e5) >>> 1; - char a3 = a[e3]; - - /* - * Sort these elements in place by the combination - * of 4-element sorting network and insertion sort. - * - * 5 ------o-----------o------------ - * | | - * 4 ------|-----o-----o-----o------ - * | | | - * 2 ------o-----|-----o-----o------ - * | | - * 1 ------------o-----o------------ - */ - if (a[e5] < a[e2]) { char t = a[e5]; a[e5] = a[e2]; a[e2] = t; } - if (a[e4] < a[e1]) { char t = a[e4]; a[e4] = a[e1]; a[e1] = t; } - if (a[e5] < a[e4]) { char t = a[e5]; a[e5] = a[e4]; a[e4] = t; } - if (a[e2] < a[e1]) { char t = a[e2]; a[e2] = a[e1]; a[e1] = t; } - if (a[e4] < a[e2]) { char t = a[e4]; a[e4] = a[e2]; a[e2] = t; } - - if (a3 < a[e2]) { - if (a3 < a[e1]) { - a[e3] = a[e2]; a[e2] = a[e1]; a[e1] = a3; - } else { - a[e3] = a[e2]; a[e2] = a3; - } - } else if (a3 > a[e4]) { - if (a3 > a[e5]) { - a[e3] = a[e4]; a[e4] = a[e5]; a[e5] = a3; - } else { - a[e3] = a[e4]; a[e4] = a3; - } - } - - // Pointers - int lower = low; // The index of the last element of the left part - int upper = end; // The index of the first element of the right part - - /* - * Partitioning with 2 pivots in case of different elements. - */ - if (a[e1] < a[e2] && a[e2] < a[e3] && a[e3] < a[e4] && a[e4] < a[e5]) { - - /* - * Use the first and fifth of the five sorted elements as - * the pivots. These values are inexpensive approximation - * of tertiles. Note, that pivot1 < pivot2. - */ - char pivot1 = a[e1]; - char pivot2 = a[e5]; - - /* - * The first and the last elements to be sorted are moved - * to the locations formerly occupied by the pivots. When - * partitioning is completed, the pivots are swapped back - * into their final positions, and excluded from the next - * subsequent sorting. - */ - a[e1] = a[lower]; - a[e5] = a[upper]; - - /* - * Skip elements, which are less or greater than the pivots. - */ - while (a[++lower] < pivot1); - while (a[--upper] > pivot2); - - /* - * Backward 3-interval partitioning - * - * left part central part right part - * +------------------------------------------------------------+ - * | < pivot1 | ? | pivot1 <= && <= pivot2 | > pivot2 | - * +------------------------------------------------------------+ - * ^ ^ ^ - * | | | - * lower k upper - * - * Invariants: - * - * all in (low, lower] < pivot1 - * pivot1 <= all in (k, upper) <= pivot2 - * all in [upper, end) > pivot2 - * - * Pointer k is the last index of ?-part - */ - for (int unused = --lower, k = ++upper; --k > lower; ) { - char ak = a[k]; - - if (ak < pivot1) { // Move a[k] to the left side - while (lower < k) { - if (a[++lower] >= pivot1) { - if (a[lower] > pivot2) { - a[k] = a[--upper]; - a[upper] = a[lower]; - } else { - a[k] = a[lower]; - } - a[lower] = ak; - break; - } - } - } else if (ak > pivot2) { // Move a[k] to the right side - a[k] = a[--upper]; - a[upper] = ak; - } - } - - /* - * Swap the pivots into their final positions. - */ - a[low] = a[lower]; a[lower] = pivot1; - a[end] = a[upper]; a[upper] = pivot2; - - /* - * Sort non-left parts recursively, - * excluding known pivots. - */ - sort(a, bits | 1, lower + 1, upper); - sort(a, bits | 1, upper + 1, high); - - } else { // Use single pivot in case of many equal elements - - /* - * Use the third of the five sorted elements as the pivot. - * This value is inexpensive approximation of the median. - */ - char pivot = a[e3]; - - /* - * The first element to be sorted is moved to the - * location formerly occupied by the pivot. After - * completion of partitioning the pivot is swapped - * back into its final position, and excluded from - * the next subsequent sorting. - */ - a[e3] = a[lower]; - - /* - * Traditional 3-way (Dutch National Flag) partitioning - * - * left part central part right part - * +------------------------------------------------------+ - * | < pivot | ? | == pivot | > pivot | - * +------------------------------------------------------+ - * ^ ^ ^ - * | | | - * lower k upper - * - * Invariants: - * - * all in (low, lower] < pivot - * all in (k, upper) == pivot - * all in [upper, end] > pivot - * - * Pointer k is the last index of ?-part - */ - for (int k = ++upper; --k > lower; ) { - char ak = a[k]; - - if (ak != pivot) { - a[k] = pivot; - - if (ak < pivot) { // Move a[k] to the left side - while (a[++lower] < pivot); - - if (a[lower] > pivot) { - a[--upper] = a[lower]; - } - a[lower] = ak; - } else { // ak > pivot - Move a[k] to the right side - a[--upper] = ak; - } - } - } - - /* - * Swap the pivot into its final position. - */ - a[low] = a[lower]; a[lower] = pivot; - - /* - * Sort the right part, excluding known pivot. - * All elements from the central part are - * equal and therefore already sorted. - */ - sort(a, bits | 1, upper, high); - } - high = lower; // Iterate along the left part - } - } - - /** - * Sorts the specified range of the array using insertion sort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void insertionSort(char[] a, int low, int high) { - for (int i, k = low; ++k < high; ) { - char ai = a[i = k]; - - if (ai < a[i - 1]) { - while (--i >= low && ai < a[i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - } - } - } - - /** - * The number of distinct char values. - */ - private static final int NUM_CHAR_VALUES = 1 << 16; - - /** - * Sorts the specified range of the array using counting sort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void countingSort(char[] a, int low, int high) { - int[] count = new int[NUM_CHAR_VALUES]; - - /* - * Compute a histogram with the number of each values. - */ - for (int i = high; i > low; ++count[a[--i]]); - - /* - * Place values on their final positions. - */ - if (high - low > NUM_CHAR_VALUES) { - for (int i = NUM_CHAR_VALUES; i > 0; ) { - for (low = high - count[--i]; high > low; - a[--high] = (char) i - ); - } - } else { - for (int i = NUM_CHAR_VALUES; high > low; ) { - while (count[--i] == 0); - int c = count[i]; - - do { - a[--high] = (char) i; - } while (--c > 0); - } - } - } - -// [short] - - /** - * Sorts the specified range of the array using - * counting sort or Dual-Pivot Quicksort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - static void sort(short[] a, int low, int high) { - if (high - low > MIN_SHORT_OR_CHAR_COUNTING_SORT_SIZE) { - countingSort(a, low, high); - } else { - sort(a, 0, low, high); - } - } - - /** - * Sorts the specified array using the Dual-Pivot Quicksort and/or - * other sorts in special-cases, possibly with parallel partitions. - * - * @param a the array to be sorted - * @param bits the combination of recursion depth and bit flag, where - * the right bit "0" indicates that array is the leftmost part - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - static void sort(short[] a, int bits, int low, int high) { - while (true) { - int end = high - 1, size = high - low; - - /* - * Invoke insertion sort on small leftmost part. - */ - if (size < MAX_INSERTION_SORT_SIZE) { - insertionSort(a, low, high); - return; - } - - /* - * Switch to counting sort if execution - * time is becoming quadratic. - */ - if ((bits += DELTA) > MAX_RECURSION_DEPTH) { - countingSort(a, low, high); - return; - } - - /* - * Use an inexpensive approximation of the golden ratio - * to select five sample elements and determine pivots. - */ - int step = (size >> 3) * 3 + 3; - - /* - * Five elements around (and including) the central element - * will be used for pivot selection as described below. The - * unequal choice of spacing these elements was empirically - * determined to work well on a wide variety of inputs. - */ - int e1 = low + step; - int e5 = end - step; - int e3 = (e1 + e5) >>> 1; - int e2 = (e1 + e3) >>> 1; - int e4 = (e3 + e5) >>> 1; - short a3 = a[e3]; - - /* - * Sort these elements in place by the combination - * of 4-element sorting network and insertion sort. - * - * 5 ------o-----------o------------ - * | | - * 4 ------|-----o-----o-----o------ - * | | | - * 2 ------o-----|-----o-----o------ - * | | - * 1 ------------o-----o------------ - */ - if (a[e5] < a[e2]) { short t = a[e5]; a[e5] = a[e2]; a[e2] = t; } - if (a[e4] < a[e1]) { short t = a[e4]; a[e4] = a[e1]; a[e1] = t; } - if (a[e5] < a[e4]) { short t = a[e5]; a[e5] = a[e4]; a[e4] = t; } - if (a[e2] < a[e1]) { short t = a[e2]; a[e2] = a[e1]; a[e1] = t; } - if (a[e4] < a[e2]) { short t = a[e4]; a[e4] = a[e2]; a[e2] = t; } - - if (a3 < a[e2]) { - if (a3 < a[e1]) { - a[e3] = a[e2]; a[e2] = a[e1]; a[e1] = a3; - } else { - a[e3] = a[e2]; a[e2] = a3; - } - } else if (a3 > a[e4]) { - if (a3 > a[e5]) { - a[e3] = a[e4]; a[e4] = a[e5]; a[e5] = a3; - } else { - a[e3] = a[e4]; a[e4] = a3; - } - } - - // Pointers - int lower = low; // The index of the last element of the left part - int upper = end; // The index of the first element of the right part - - /* - * Partitioning with 2 pivots in case of different elements. - */ - if (a[e1] < a[e2] && a[e2] < a[e3] && a[e3] < a[e4] && a[e4] < a[e5]) { - - /* - * Use the first and fifth of the five sorted elements as - * the pivots. These values are inexpensive approximation - * of tertiles. Note, that pivot1 < pivot2. - */ - short pivot1 = a[e1]; - short pivot2 = a[e5]; - - /* - * The first and the last elements to be sorted are moved - * to the locations formerly occupied by the pivots. When - * partitioning is completed, the pivots are swapped back - * into their final positions, and excluded from the next - * subsequent sorting. - */ - a[e1] = a[lower]; - a[e5] = a[upper]; - - /* - * Skip elements, which are less or greater than the pivots. - */ - while (a[++lower] < pivot1); - while (a[--upper] > pivot2); - - /* - * Backward 3-interval partitioning - * - * left part central part right part - * +------------------------------------------------------------+ - * | < pivot1 | ? | pivot1 <= && <= pivot2 | > pivot2 | - * +------------------------------------------------------------+ - * ^ ^ ^ - * | | | - * lower k upper - * - * Invariants: - * - * all in (low, lower] < pivot1 - * pivot1 <= all in (k, upper) <= pivot2 - * all in [upper, end) > pivot2 - * - * Pointer k is the last index of ?-part - */ - for (int unused = --lower, k = ++upper; --k > lower; ) { - short ak = a[k]; - - if (ak < pivot1) { // Move a[k] to the left side - while (lower < k) { - if (a[++lower] >= pivot1) { - if (a[lower] > pivot2) { - a[k] = a[--upper]; - a[upper] = a[lower]; - } else { - a[k] = a[lower]; - } - a[lower] = ak; - break; - } - } - } else if (ak > pivot2) { // Move a[k] to the right side - a[k] = a[--upper]; - a[upper] = ak; - } - } - - /* - * Swap the pivots into their final positions. - */ - a[low] = a[lower]; a[lower] = pivot1; - a[end] = a[upper]; a[upper] = pivot2; - - /* - * Sort non-left parts recursively, - * excluding known pivots. - */ - sort(a, bits | 1, lower + 1, upper); - sort(a, bits | 1, upper + 1, high); - - } else { // Use single pivot in case of many equal elements - - /* - * Use the third of the five sorted elements as the pivot. - * This value is inexpensive approximation of the median. - */ - short pivot = a[e3]; - - /* - * The first element to be sorted is moved to the - * location formerly occupied by the pivot. After - * completion of partitioning the pivot is swapped - * back into its final position, and excluded from - * the next subsequent sorting. - */ - a[e3] = a[lower]; - - /* - * Traditional 3-way (Dutch National Flag) partitioning - * - * left part central part right part - * +------------------------------------------------------+ - * | < pivot | ? | == pivot | > pivot | - * +------------------------------------------------------+ - * ^ ^ ^ - * | | | - * lower k upper - * - * Invariants: - * - * all in (low, lower] < pivot - * all in (k, upper) == pivot - * all in [upper, end] > pivot - * - * Pointer k is the last index of ?-part - */ - for (int k = ++upper; --k > lower; ) { - short ak = a[k]; - - if (ak != pivot) { - a[k] = pivot; - - if (ak < pivot) { // Move a[k] to the left side - while (a[++lower] < pivot); - - if (a[lower] > pivot) { - a[--upper] = a[lower]; - } - a[lower] = ak; - } else { // ak > pivot - Move a[k] to the right side - a[--upper] = ak; - } - } - } - - /* - * Swap the pivot into its final position. - */ - a[low] = a[lower]; a[lower] = pivot; - - /* - * Sort the right part, excluding known pivot. - * All elements from the central part are - * equal and therefore already sorted. - */ - sort(a, bits | 1, upper, high); - } - high = lower; // Iterate along the left part - } - } - - /** - * Sorts the specified range of the array using insertion sort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void insertionSort(short[] a, int low, int high) { - for (int i, k = low; ++k < high; ) { - short ai = a[i = k]; - - if (ai < a[i - 1]) { - while (--i >= low && ai < a[i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - } - } - } - - /** - * The number of distinct short values. - */ - private static final int NUM_SHORT_VALUES = 1 << 16; - - /** - * Max index of short counter. - */ - private static final int MAX_SHORT_INDEX = Short.MAX_VALUE + NUM_SHORT_VALUES + 1; - - /** - * Sorts the specified range of the array using counting sort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void countingSort(short[] a, int low, int high) { - int[] count = new int[NUM_SHORT_VALUES]; - - /* - * Compute a histogram with the number of each values. - */ - for (int i = high; i > low; ++count[a[--i] & 0xFFFF]); - - /* - * Place values on their final positions. - */ - if (high - low > NUM_SHORT_VALUES) { - for (int i = MAX_SHORT_INDEX; --i > Short.MAX_VALUE; ) { - int value = i & 0xFFFF; - - for (low = high - count[value]; high > low; - a[--high] = (short) value - ); - } - } else { - for (int i = MAX_SHORT_INDEX; high > low; ) { - while (count[--i & 0xFFFF] == 0); - - int value = i & 0xFFFF; - int c = count[value]; - - do { - a[--high] = (short) value; - } while (--c > 0); - } - } - } - -// [float] - - /** - * Sorts the specified range of the array using parallel merge - * sort and/or Dual-Pivot Quicksort. - * - * To balance the faster splitting and parallelism of merge sort - * with the faster element partitioning of Quicksort, ranges are - * subdivided in tiers such that, if there is enough parallelism, - * the four-way parallel merge is started, still ensuring enough - * parallelism to process the partitions. - * - * @param a the array to be sorted - * @param parallelism the parallelism level - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - static void sort(float[] a, int parallelism, int low, int high) { - /* - * Phase 1. Count the number of negative zero -0.0f, - * turn them into positive zero, and move all NaNs - * to the end of the array. - */ - int numNegativeZero = 0; - - for (int k = high; k > low; ) { - float ak = a[--k]; - - if (ak == 0.0f && Float.floatToRawIntBits(ak) < 0) { // ak is -0.0f - numNegativeZero += 1; - a[k] = 0.0f; - } else if (ak != ak) { // ak is NaN - a[k] = a[--high]; - a[high] = ak; - } - } - - /* - * Phase 2. Sort everything except NaNs, - * which are already in place. - */ - int size = high - low; - - if (parallelism > 1 && size > MIN_PARALLEL_SORT_SIZE) { - int depth = getDepth(parallelism, size >> 12); - float[] b = depth == 0 ? null : new float[size]; - new Sorter(null, a, b, low, size, low, depth).invoke(); - } else { - sort(null, a, 0, low, high); - } - - /* - * Phase 3. Turn positive zero 0.0f - * back into negative zero -0.0f. - */ - if (++numNegativeZero == 1) { - return; - } - - /* - * Find the position one less than - * the index of the first zero. - */ - while (low <= high) { - int middle = (low + high) >>> 1; - - if (a[middle] < 0) { - low = middle + 1; - } else { - high = middle - 1; - } - } - - /* - * Replace the required number of 0.0f by -0.0f. - */ - while (--numNegativeZero > 0) { - a[++high] = -0.0f; - } - } - - /** - * Sorts the specified array using the Dual-Pivot Quicksort and/or - * other sorts in special-cases, possibly with parallel partitions. - * - * @param sorter parallel context - * @param a the array to be sorted - * @param bits the combination of recursion depth and bit flag, where - * the right bit "0" indicates that array is the leftmost part - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - static void sort(Sorter sorter, float[] a, int bits, int low, int high) { - while (true) { - int end = high - 1, size = high - low; - - /* - * Run mixed insertion sort on small non-leftmost parts. - */ - if (size < MAX_MIXED_INSERTION_SORT_SIZE + bits && (bits & 1) > 0) { - mixedInsertionSort(a, low, high - 3 * ((size >> 5) << 3), high); - return; - } - - /* - * Invoke insertion sort on small leftmost part. - */ - if (size < MAX_INSERTION_SORT_SIZE) { - insertionSort(a, low, high); - return; - } - - /* - * Check if the whole array or large non-leftmost - * parts are nearly sorted and then merge runs. - */ - if ((bits == 0 || size > MIN_TRY_MERGE_SIZE && (bits & 1) > 0) - && tryMergeRuns(sorter, a, low, size)) { - return; - } - - /* - * Switch to heap sort if execution - * time is becoming quadratic. - */ - if ((bits += DELTA) > MAX_RECURSION_DEPTH) { - heapSort(a, low, high); - return; - } - - /* - * Use an inexpensive approximation of the golden ratio - * to select five sample elements and determine pivots. - */ - int step = (size >> 3) * 3 + 3; - - /* - * Five elements around (and including) the central element - * will be used for pivot selection as described below. The - * unequal choice of spacing these elements was empirically - * determined to work well on a wide variety of inputs. - */ - int e1 = low + step; - int e5 = end - step; - int e3 = (e1 + e5) >>> 1; - int e2 = (e1 + e3) >>> 1; - int e4 = (e3 + e5) >>> 1; - float a3 = a[e3]; - - /* - * Sort these elements in place by the combination - * of 4-element sorting network and insertion sort. - * - * 5 ------o-----------o------------ - * | | - * 4 ------|-----o-----o-----o------ - * | | | - * 2 ------o-----|-----o-----o------ - * | | - * 1 ------------o-----o------------ - */ - if (a[e5] < a[e2]) { float t = a[e5]; a[e5] = a[e2]; a[e2] = t; } - if (a[e4] < a[e1]) { float t = a[e4]; a[e4] = a[e1]; a[e1] = t; } - if (a[e5] < a[e4]) { float t = a[e5]; a[e5] = a[e4]; a[e4] = t; } - if (a[e2] < a[e1]) { float t = a[e2]; a[e2] = a[e1]; a[e1] = t; } - if (a[e4] < a[e2]) { float t = a[e4]; a[e4] = a[e2]; a[e2] = t; } - - if (a3 < a[e2]) { - if (a3 < a[e1]) { - a[e3] = a[e2]; a[e2] = a[e1]; a[e1] = a3; - } else { - a[e3] = a[e2]; a[e2] = a3; - } - } else if (a3 > a[e4]) { - if (a3 > a[e5]) { - a[e3] = a[e4]; a[e4] = a[e5]; a[e5] = a3; - } else { - a[e3] = a[e4]; a[e4] = a3; - } - } - - // Pointers - int lower = low; // The index of the last element of the left part - int upper = end; // The index of the first element of the right part - - /* - * Partitioning with 2 pivots in case of different elements. - */ - if (a[e1] < a[e2] && a[e2] < a[e3] && a[e3] < a[e4] && a[e4] < a[e5]) { - - /* - * Use the first and fifth of the five sorted elements as - * the pivots. These values are inexpensive approximation - * of tertiles. Note, that pivot1 < pivot2. - */ - float pivot1 = a[e1]; - float pivot2 = a[e5]; - - /* - * The first and the last elements to be sorted are moved - * to the locations formerly occupied by the pivots. When - * partitioning is completed, the pivots are swapped back - * into their final positions, and excluded from the next - * subsequent sorting. - */ - a[e1] = a[lower]; - a[e5] = a[upper]; - - /* - * Skip elements, which are less or greater than the pivots. - */ - while (a[++lower] < pivot1); - while (a[--upper] > pivot2); - - /* - * Backward 3-interval partitioning - * - * left part central part right part - * +------------------------------------------------------------+ - * | < pivot1 | ? | pivot1 <= && <= pivot2 | > pivot2 | - * +------------------------------------------------------------+ - * ^ ^ ^ - * | | | - * lower k upper - * - * Invariants: - * - * all in (low, lower] < pivot1 - * pivot1 <= all in (k, upper) <= pivot2 - * all in [upper, end) > pivot2 - * - * Pointer k is the last index of ?-part - */ - for (int unused = --lower, k = ++upper; --k > lower; ) { - float ak = a[k]; - - if (ak < pivot1) { // Move a[k] to the left side - while (lower < k) { - if (a[++lower] >= pivot1) { - if (a[lower] > pivot2) { - a[k] = a[--upper]; - a[upper] = a[lower]; - } else { - a[k] = a[lower]; - } - a[lower] = ak; - break; - } - } - } else if (ak > pivot2) { // Move a[k] to the right side - a[k] = a[--upper]; - a[upper] = ak; - } - } - - /* - * Swap the pivots into their final positions. - */ - a[low] = a[lower]; a[lower] = pivot1; - a[end] = a[upper]; a[upper] = pivot2; - - /* - * Sort non-left parts recursively (possibly in parallel), - * excluding known pivots. - */ - if (size > MIN_PARALLEL_SORT_SIZE && sorter != null) { - sorter.forkSorter(bits | 1, lower + 1, upper); - sorter.forkSorter(bits | 1, upper + 1, high); - } else { - sort(sorter, a, bits | 1, lower + 1, upper); - sort(sorter, a, bits | 1, upper + 1, high); - } - - } else { // Use single pivot in case of many equal elements - - /* - * Use the third of the five sorted elements as the pivot. - * This value is inexpensive approximation of the median. - */ - float pivot = a[e3]; - - /* - * The first element to be sorted is moved to the - * location formerly occupied by the pivot. After - * completion of partitioning the pivot is swapped - * back into its final position, and excluded from - * the next subsequent sorting. - */ - a[e3] = a[lower]; - - /* - * Traditional 3-way (Dutch National Flag) partitioning - * - * left part central part right part - * +------------------------------------------------------+ - * | < pivot | ? | == pivot | > pivot | - * +------------------------------------------------------+ - * ^ ^ ^ - * | | | - * lower k upper - * - * Invariants: - * - * all in (low, lower] < pivot - * all in (k, upper) == pivot - * all in [upper, end] > pivot - * - * Pointer k is the last index of ?-part - */ - for (int k = ++upper; --k > lower; ) { - float ak = a[k]; - - if (ak != pivot) { - a[k] = pivot; - - if (ak < pivot) { // Move a[k] to the left side - while (a[++lower] < pivot); - - if (a[lower] > pivot) { - a[--upper] = a[lower]; - } - a[lower] = ak; - } else { // ak > pivot - Move a[k] to the right side - a[--upper] = ak; - } - } - } - - /* - * Swap the pivot into its final position. - */ - a[low] = a[lower]; a[lower] = pivot; - - /* - * Sort the right part (possibly in parallel), excluding - * known pivot. All elements from the central part are - * equal and therefore already sorted. - */ - if (size > MIN_PARALLEL_SORT_SIZE && sorter != null) { - sorter.forkSorter(bits | 1, upper, high); - } else { - sort(sorter, a, bits | 1, upper, high); - } - } - high = lower; // Iterate along the left part - } - } - - /** - * Sorts the specified range of the array using mixed insertion sort. - * - * Mixed insertion sort is combination of simple insertion sort, - * pin insertion sort and pair insertion sort. - * - * In the context of Dual-Pivot Quicksort, the pivot element - * from the left part plays the role of sentinel, because it - * is less than any elements from the given part. Therefore, - * expensive check of the left range can be skipped on each - * iteration unless it is the leftmost call. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param end the index of the last element for simple insertion sort - * @param high the index of the last element, exclusive, to be sorted - */ - private static void mixedInsertionSort(float[] a, int low, int end, int high) { - if (end == high) { - - /* - * Invoke simple insertion sort on tiny array. - */ - for (int i; ++low < end; ) { - float ai = a[i = low]; - - while (ai < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - } - } else { - - /* - * Start with pin insertion sort on small part. - * - * Pin insertion sort is extended simple insertion sort. - * The main idea of this sort is to put elements larger - * than an element called pin to the end of array (the - * proper area for such elements). It avoids expensive - * movements of these elements through the whole array. - */ - float pin = a[end]; - - for (int i, p = high; ++low < end; ) { - float ai = a[i = low]; - - if (ai < a[i - 1]) { // Small element - - /* - * Insert small element into sorted part. - */ - a[i] = a[--i]; - - while (ai < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - - } else if (p > i && ai > pin) { // Large element - - /* - * Find element smaller than pin. - */ - while (a[--p] > pin); - - /* - * Swap it with large element. - */ - if (p > i) { - ai = a[p]; - a[p] = a[i]; - } - - /* - * Insert small element into sorted part. - */ - while (ai < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - } - } - - /* - * Continue with pair insertion sort on remain part. - */ - for (int i; low < high; ++low) { - float a1 = a[i = low], a2 = a[++low]; - - /* - * Insert two elements per iteration: at first, insert the - * larger element and then insert the smaller element, but - * from the position where the larger element was inserted. - */ - if (a1 > a2) { - - while (a1 < a[--i]) { - a[i + 2] = a[i]; - } - a[++i + 1] = a1; - - while (a2 < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = a2; - - } else if (a1 < a[i - 1]) { - - while (a2 < a[--i]) { - a[i + 2] = a[i]; - } - a[++i + 1] = a2; - - while (a1 < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = a1; - } - } - } - } - - /** - * Sorts the specified range of the array using insertion sort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void insertionSort(float[] a, int low, int high) { - for (int i, k = low; ++k < high; ) { - float ai = a[i = k]; - - if (ai < a[i - 1]) { - while (--i >= low && ai < a[i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - } - } - } - - /** - * Sorts the specified range of the array using heap sort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void heapSort(float[] a, int low, int high) { - for (int k = (low + high) >>> 1; k > low; ) { - pushDown(a, --k, a[k], low, high); - } - while (--high > low) { - float max = a[low]; - pushDown(a, low, a[high], low, high); - a[high] = max; - } - } - - /** - * Pushes specified element down during heap sort. - * - * @param a the given array - * @param p the start index - * @param value the given element - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void pushDown(float[] a, int p, float value, int low, int high) { - for (int k ;; a[p] = a[p = k]) { - k = (p << 1) - low + 2; // Index of the right child - - if (k > high) { - break; - } - if (k == high || a[k] < a[k - 1]) { - --k; - } - if (a[k] <= value) { - break; - } - } - a[p] = value; - } - - /** - * Tries to sort the specified range of the array. - * - * @param sorter parallel context - * @param a the array to be sorted - * @param low the index of the first element to be sorted - * @param size the array size - * @return true if finally sorted, false otherwise - */ - private static boolean tryMergeRuns(Sorter sorter, float[] a, int low, int size) { - - /* - * The run array is constructed only if initial runs are - * long enough to continue, run[i] then holds start index - * of the i-th sequence of elements in non-descending order. - */ - int[] run = null; - int high = low + size; - int count = 1, last = low; - - /* - * Identify all possible runs. - */ - for (int k = low + 1; k < high; ) { - - /* - * Find the end index of the current run. - */ - if (a[k - 1] < a[k]) { - - // Identify ascending sequence - while (++k < high && a[k - 1] <= a[k]); - - } else if (a[k - 1] > a[k]) { - - // Identify descending sequence - while (++k < high && a[k - 1] >= a[k]); - - // Reverse into ascending order - for (int i = last - 1, j = k; ++i < --j && a[i] > a[j]; ) { - float ai = a[i]; a[i] = a[j]; a[j] = ai; - } - } else { // Identify constant sequence - for (float ak = a[k]; ++k < high && ak == a[k]; ); - - if (k < high) { - continue; - } - } - - /* - * Check special cases. - */ - if (run == null) { - if (k == high) { - - /* - * The array is monotonous sequence, - * and therefore already sorted. - */ - return true; - } - - if (k - low < MIN_FIRST_RUN_SIZE) { - - /* - * The first run is too small - * to proceed with scanning. - */ - return false; - } - - run = new int[((size >> 10) | 0x7F) & 0x3FF]; - run[0] = low; - - } else if (a[last - 1] > a[last]) { - - if (count > (k - low) >> MIN_FIRST_RUNS_FACTOR) { - - /* - * The first runs are not long - * enough to continue scanning. - */ - return false; - } - - if (++count == MAX_RUN_CAPACITY) { - - /* - * Array is not highly structured. - */ - return false; - } - - if (count == run.length) { - - /* - * Increase capacity of index array. - */ - run = Arrays.copyOf(run, count << 1); - } - } - run[count] = (last = k); - } - - /* - * Merge runs of highly structured array. - */ - if (count > 1) { - float[] b; int offset = low; - - if (sorter == null || (b = (float[]) sorter.b) == null) { - b = new float[size]; - } else { - offset = sorter.offset; - } - mergeRuns(a, b, offset, 1, sorter != null, run, 0, count); - } - return true; - } - - /** - * Merges the specified runs. - * - * @param a the source array - * @param b the temporary buffer used in merging - * @param offset the start index in the source, inclusive - * @param aim specifies merging: to source ( > 0), buffer ( < 0) or any ( == 0) - * @param parallel indicates whether merging is performed in parallel - * @param run the start indexes of the runs, inclusive - * @param lo the start index of the first run, inclusive - * @param hi the start index of the last run, inclusive - * @return the destination where runs are merged - */ - private static float[] mergeRuns(float[] a, float[] b, int offset, - int aim, boolean parallel, int[] run, int lo, int hi) { - - if (hi - lo == 1) { - if (aim >= 0) { - return a; - } - for (int i = run[hi], j = i - offset, low = run[lo]; i > low; - b[--j] = a[--i] - ); - return b; - } - - /* - * Split into approximately equal parts. - */ - int mi = lo, rmi = (run[lo] + run[hi]) >>> 1; - while (run[++mi + 1] <= rmi); - - /* - * Merge the left and right parts. - */ - float[] a1, a2; - - if (parallel && hi - lo > MIN_RUN_COUNT) { - RunMerger merger = new RunMerger(a, b, offset, 0, run, mi, hi).forkMe(); - a1 = mergeRuns(a, b, offset, -aim, true, run, lo, mi); - a2 = (float[]) merger.getDestination(); - } else { - a1 = mergeRuns(a, b, offset, -aim, false, run, lo, mi); - a2 = mergeRuns(a, b, offset, 0, false, run, mi, hi); - } - - float[] dst = a1 == a ? b : a; - - int k = a1 == a ? run[lo] - offset : run[lo]; - int lo1 = a1 == b ? run[lo] - offset : run[lo]; - int hi1 = a1 == b ? run[mi] - offset : run[mi]; - int lo2 = a2 == b ? run[mi] - offset : run[mi]; - int hi2 = a2 == b ? run[hi] - offset : run[hi]; - - if (parallel) { - new Merger(null, dst, k, a1, lo1, hi1, a2, lo2, hi2).invoke(); - } else { - mergeParts(null, dst, k, a1, lo1, hi1, a2, lo2, hi2); - } - return dst; - } - - /** - * Merges the sorted parts. - * - * @param merger parallel context - * @param dst the destination where parts are merged - * @param k the start index of the destination, inclusive - * @param a1 the first part - * @param lo1 the start index of the first part, inclusive - * @param hi1 the end index of the first part, exclusive - * @param a2 the second part - * @param lo2 the start index of the second part, inclusive - * @param hi2 the end index of the second part, exclusive - */ - private static void mergeParts(Merger merger, float[] dst, int k, - float[] a1, int lo1, int hi1, float[] a2, int lo2, int hi2) { - - if (merger != null && a1 == a2) { - - while (true) { - - /* - * The first part must be larger. - */ - if (hi1 - lo1 < hi2 - lo2) { - int lo = lo1; lo1 = lo2; lo2 = lo; - int hi = hi1; hi1 = hi2; hi2 = hi; - } - - /* - * Small parts will be merged sequentially. - */ - if (hi1 - lo1 < MIN_PARALLEL_MERGE_PARTS_SIZE) { - break; - } - - /* - * Find the median of the larger part. - */ - int mi1 = (lo1 + hi1) >>> 1; - float key = a1[mi1]; - int mi2 = hi2; - - /* - * Partition the smaller part. - */ - for (int loo = lo2; loo < mi2; ) { - int t = (loo + mi2) >>> 1; - - if (key > a2[t]) { - loo = t + 1; - } else { - mi2 = t; - } - } - - int d = mi2 - lo2 + mi1 - lo1; - - /* - * Merge the right sub-parts in parallel. - */ - merger.forkMerger(dst, k + d, a1, mi1, hi1, a2, mi2, hi2); - - /* - * Process the sub-left parts. - */ - hi1 = mi1; - hi2 = mi2; - } - } - - /* - * Merge small parts sequentially. - */ - while (lo1 < hi1 && lo2 < hi2) { - dst[k++] = a1[lo1] < a2[lo2] ? a1[lo1++] : a2[lo2++]; - } - if (dst != a1 || k < lo1) { - while (lo1 < hi1) { - dst[k++] = a1[lo1++]; - } - } - if (dst != a2 || k < lo2) { - while (lo2 < hi2) { - dst[k++] = a2[lo2++]; - } - } - } - -// [double] - - /** - * Sorts the specified range of the array using parallel merge - * sort and/or Dual-Pivot Quicksort. - * - * To balance the faster splitting and parallelism of merge sort - * with the faster element partitioning of Quicksort, ranges are - * subdivided in tiers such that, if there is enough parallelism, - * the four-way parallel merge is started, still ensuring enough - * parallelism to process the partitions. - * - * @param a the array to be sorted - * @param parallelism the parallelism level - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - static void sort(double[] a, int parallelism, int low, int high) { - /* - * Phase 1. Count the number of negative zero -0.0d, - * turn them into positive zero, and move all NaNs - * to the end of the array. - */ - int numNegativeZero = 0; - - for (int k = high; k > low; ) { - double ak = a[--k]; - - if (ak == 0.0d && Double.doubleToRawLongBits(ak) < 0) { // ak is -0.0d - numNegativeZero += 1; - a[k] = 0.0d; - } else if (ak != ak) { // ak is NaN - a[k] = a[--high]; - a[high] = ak; - } - } - - /* - * Phase 2. Sort everything except NaNs, - * which are already in place. - */ - int size = high - low; - - if (parallelism > 1 && size > MIN_PARALLEL_SORT_SIZE) { - int depth = getDepth(parallelism, size >> 12); - double[] b = depth == 0 ? null : new double[size]; - new Sorter(null, a, b, low, size, low, depth).invoke(); - } else { - sort(null, a, 0, low, high); - } - - /* - * Phase 3. Turn positive zero 0.0d - * back into negative zero -0.0d. - */ - if (++numNegativeZero == 1) { - return; - } - - /* - * Find the position one less than - * the index of the first zero. - */ - while (low <= high) { - int middle = (low + high) >>> 1; - - if (a[middle] < 0) { - low = middle + 1; - } else { - high = middle - 1; - } - } - - /* - * Replace the required number of 0.0d by -0.0d. - */ - while (--numNegativeZero > 0) { - a[++high] = -0.0d; - } - } - - /** - * Sorts the specified array using the Dual-Pivot Quicksort and/or - * other sorts in special-cases, possibly with parallel partitions. - * - * @param sorter parallel context - * @param a the array to be sorted - * @param bits the combination of recursion depth and bit flag, where - * the right bit "0" indicates that array is the leftmost part - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - static void sort(Sorter sorter, double[] a, int bits, int low, int high) { - while (true) { - int end = high - 1, size = high - low; - - /* - * Run mixed insertion sort on small non-leftmost parts. - */ - if (size < MAX_MIXED_INSERTION_SORT_SIZE + bits && (bits & 1) > 0) { - mixedInsertionSort(a, low, high - 3 * ((size >> 5) << 3), high); - return; - } - - /* - * Invoke insertion sort on small leftmost part. - */ - if (size < MAX_INSERTION_SORT_SIZE) { - insertionSort(a, low, high); - return; - } - - /* - * Check if the whole array or large non-leftmost - * parts are nearly sorted and then merge runs. - */ - if ((bits == 0 || size > MIN_TRY_MERGE_SIZE && (bits & 1) > 0) - && tryMergeRuns(sorter, a, low, size)) { - return; - } - - /* - * Switch to heap sort if execution - * time is becoming quadratic. - */ - if ((bits += DELTA) > MAX_RECURSION_DEPTH) { - heapSort(a, low, high); - return; - } - - /* - * Use an inexpensive approximation of the golden ratio - * to select five sample elements and determine pivots. - */ - int step = (size >> 3) * 3 + 3; - - /* - * Five elements around (and including) the central element - * will be used for pivot selection as described below. The - * unequal choice of spacing these elements was empirically - * determined to work well on a wide variety of inputs. - */ - int e1 = low + step; - int e5 = end - step; - int e3 = (e1 + e5) >>> 1; - int e2 = (e1 + e3) >>> 1; - int e4 = (e3 + e5) >>> 1; - double a3 = a[e3]; - - /* - * Sort these elements in place by the combination - * of 4-element sorting network and insertion sort. - * - * 5 ------o-----------o------------ - * | | - * 4 ------|-----o-----o-----o------ - * | | | - * 2 ------o-----|-----o-----o------ - * | | - * 1 ------------o-----o------------ - */ - if (a[e5] < a[e2]) { double t = a[e5]; a[e5] = a[e2]; a[e2] = t; } - if (a[e4] < a[e1]) { double t = a[e4]; a[e4] = a[e1]; a[e1] = t; } - if (a[e5] < a[e4]) { double t = a[e5]; a[e5] = a[e4]; a[e4] = t; } - if (a[e2] < a[e1]) { double t = a[e2]; a[e2] = a[e1]; a[e1] = t; } - if (a[e4] < a[e2]) { double t = a[e4]; a[e4] = a[e2]; a[e2] = t; } - - if (a3 < a[e2]) { - if (a3 < a[e1]) { - a[e3] = a[e2]; a[e2] = a[e1]; a[e1] = a3; - } else { - a[e3] = a[e2]; a[e2] = a3; - } - } else if (a3 > a[e4]) { - if (a3 > a[e5]) { - a[e3] = a[e4]; a[e4] = a[e5]; a[e5] = a3; - } else { - a[e3] = a[e4]; a[e4] = a3; - } - } - - // Pointers - int lower = low; // The index of the last element of the left part - int upper = end; // The index of the first element of the right part - - /* - * Partitioning with 2 pivots in case of different elements. - */ - if (a[e1] < a[e2] && a[e2] < a[e3] && a[e3] < a[e4] && a[e4] < a[e5]) { - - /* - * Use the first and fifth of the five sorted elements as - * the pivots. These values are inexpensive approximation - * of tertiles. Note, that pivot1 < pivot2. - */ - double pivot1 = a[e1]; - double pivot2 = a[e5]; - - /* - * The first and the last elements to be sorted are moved - * to the locations formerly occupied by the pivots. When - * partitioning is completed, the pivots are swapped back - * into their final positions, and excluded from the next - * subsequent sorting. - */ - a[e1] = a[lower]; - a[e5] = a[upper]; - - /* - * Skip elements, which are less or greater than the pivots. - */ - while (a[++lower] < pivot1); - while (a[--upper] > pivot2); - - /* - * Backward 3-interval partitioning - * - * left part central part right part - * +------------------------------------------------------------+ - * | < pivot1 | ? | pivot1 <= && <= pivot2 | > pivot2 | - * +------------------------------------------------------------+ - * ^ ^ ^ - * | | | - * lower k upper - * - * Invariants: - * - * all in (low, lower] < pivot1 - * pivot1 <= all in (k, upper) <= pivot2 - * all in [upper, end) > pivot2 - * - * Pointer k is the last index of ?-part - */ - for (int unused = --lower, k = ++upper; --k > lower; ) { - double ak = a[k]; - - if (ak < pivot1) { // Move a[k] to the left side - while (lower < k) { - if (a[++lower] >= pivot1) { - if (a[lower] > pivot2) { - a[k] = a[--upper]; - a[upper] = a[lower]; - } else { - a[k] = a[lower]; - } - a[lower] = ak; - break; - } - } - } else if (ak > pivot2) { // Move a[k] to the right side - a[k] = a[--upper]; - a[upper] = ak; - } - } - - /* - * Swap the pivots into their final positions. - */ - a[low] = a[lower]; a[lower] = pivot1; - a[end] = a[upper]; a[upper] = pivot2; - - /* - * Sort non-left parts recursively (possibly in parallel), - * excluding known pivots. - */ - if (size > MIN_PARALLEL_SORT_SIZE && sorter != null) { - sorter.forkSorter(bits | 1, lower + 1, upper); - sorter.forkSorter(bits | 1, upper + 1, high); - } else { - sort(sorter, a, bits | 1, lower + 1, upper); - sort(sorter, a, bits | 1, upper + 1, high); - } - - } else { // Use single pivot in case of many equal elements - - /* - * Use the third of the five sorted elements as the pivot. - * This value is inexpensive approximation of the median. - */ - double pivot = a[e3]; - - /* - * The first element to be sorted is moved to the - * location formerly occupied by the pivot. After - * completion of partitioning the pivot is swapped - * back into its final position, and excluded from - * the next subsequent sorting. - */ - a[e3] = a[lower]; - - /* - * Traditional 3-way (Dutch National Flag) partitioning - * - * left part central part right part - * +------------------------------------------------------+ - * | < pivot | ? | == pivot | > pivot | - * +------------------------------------------------------+ - * ^ ^ ^ - * | | | - * lower k upper - * - * Invariants: - * - * all in (low, lower] < pivot - * all in (k, upper) == pivot - * all in [upper, end] > pivot - * - * Pointer k is the last index of ?-part - */ - for (int k = ++upper; --k > lower; ) { - double ak = a[k]; - - if (ak != pivot) { - a[k] = pivot; - - if (ak < pivot) { // Move a[k] to the left side - while (a[++lower] < pivot); - - if (a[lower] > pivot) { - a[--upper] = a[lower]; - } - a[lower] = ak; - } else { // ak > pivot - Move a[k] to the right side - a[--upper] = ak; - } - } - } - - /* - * Swap the pivot into its final position. - */ - a[low] = a[lower]; a[lower] = pivot; - - /* - * Sort the right part (possibly in parallel), excluding - * known pivot. All elements from the central part are - * equal and therefore already sorted. - */ - if (size > MIN_PARALLEL_SORT_SIZE && sorter != null) { - sorter.forkSorter(bits | 1, upper, high); - } else { - sort(sorter, a, bits | 1, upper, high); - } - } - high = lower; // Iterate along the left part - } - } - - /** - * Sorts the specified range of the array using mixed insertion sort. - * - * Mixed insertion sort is combination of simple insertion sort, - * pin insertion sort and pair insertion sort. - * - * In the context of Dual-Pivot Quicksort, the pivot element - * from the left part plays the role of sentinel, because it - * is less than any elements from the given part. Therefore, - * expensive check of the left range can be skipped on each - * iteration unless it is the leftmost call. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param end the index of the last element for simple insertion sort - * @param high the index of the last element, exclusive, to be sorted - */ - private static void mixedInsertionSort(double[] a, int low, int end, int high) { - if (end == high) { - - /* - * Invoke simple insertion sort on tiny array. - */ - for (int i; ++low < end; ) { - double ai = a[i = low]; - - while (ai < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - } - } else { - - /* - * Start with pin insertion sort on small part. - * - * Pin insertion sort is extended simple insertion sort. - * The main idea of this sort is to put elements larger - * than an element called pin to the end of array (the - * proper area for such elements). It avoids expensive - * movements of these elements through the whole array. - */ - double pin = a[end]; - - for (int i, p = high; ++low < end; ) { - double ai = a[i = low]; - - if (ai < a[i - 1]) { // Small element - - /* - * Insert small element into sorted part. - */ - a[i] = a[--i]; - - while (ai < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - - } else if (p > i && ai > pin) { // Large element - - /* - * Find element smaller than pin. - */ - while (a[--p] > pin); - - /* - * Swap it with large element. - */ - if (p > i) { - ai = a[p]; - a[p] = a[i]; - } - - /* - * Insert small element into sorted part. - */ - while (ai < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - } - } - - /* - * Continue with pair insertion sort on remain part. - */ - for (int i; low < high; ++low) { - double a1 = a[i = low], a2 = a[++low]; - - /* - * Insert two elements per iteration: at first, insert the - * larger element and then insert the smaller element, but - * from the position where the larger element was inserted. - */ - if (a1 > a2) { - - while (a1 < a[--i]) { - a[i + 2] = a[i]; - } - a[++i + 1] = a1; - - while (a2 < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = a2; - - } else if (a1 < a[i - 1]) { - - while (a2 < a[--i]) { - a[i + 2] = a[i]; - } - a[++i + 1] = a2; - - while (a1 < a[--i]) { - a[i + 1] = a[i]; - } - a[i + 1] = a1; - } - } - } - } - - /** - * Sorts the specified range of the array using insertion sort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void insertionSort(double[] a, int low, int high) { - for (int i, k = low; ++k < high; ) { - double ai = a[i = k]; - - if (ai < a[i - 1]) { - while (--i >= low && ai < a[i]) { - a[i + 1] = a[i]; - } - a[i + 1] = ai; - } - } - } - - /** - * Sorts the specified range of the array using heap sort. - * - * @param a the array to be sorted - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void heapSort(double[] a, int low, int high) { - for (int k = (low + high) >>> 1; k > low; ) { - pushDown(a, --k, a[k], low, high); - } - while (--high > low) { - double max = a[low]; - pushDown(a, low, a[high], low, high); - a[high] = max; - } - } - - /** - * Pushes specified element down during heap sort. - * - * @param a the given array - * @param p the start index - * @param value the given element - * @param low the index of the first element, inclusive, to be sorted - * @param high the index of the last element, exclusive, to be sorted - */ - private static void pushDown(double[] a, int p, double value, int low, int high) { - for (int k ;; a[p] = a[p = k]) { - k = (p << 1) - low + 2; // Index of the right child - - if (k > high) { - break; - } - if (k == high || a[k] < a[k - 1]) { - --k; - } - if (a[k] <= value) { - break; - } - } - a[p] = value; - } - - /** - * Tries to sort the specified range of the array. - * - * @param sorter parallel context - * @param a the array to be sorted - * @param low the index of the first element to be sorted - * @param size the array size - * @return true if finally sorted, false otherwise - */ - private static boolean tryMergeRuns(Sorter sorter, double[] a, int low, int size) { - - /* - * The run array is constructed only if initial runs are - * long enough to continue, run[i] then holds start index - * of the i-th sequence of elements in non-descending order. - */ - int[] run = null; - int high = low + size; - int count = 1, last = low; - - /* - * Identify all possible runs. - */ - for (int k = low + 1; k < high; ) { - - /* - * Find the end index of the current run. - */ - if (a[k - 1] < a[k]) { - - // Identify ascending sequence - while (++k < high && a[k - 1] <= a[k]); - - } else if (a[k - 1] > a[k]) { - - // Identify descending sequence - while (++k < high && a[k - 1] >= a[k]); - - // Reverse into ascending order - for (int i = last - 1, j = k; ++i < --j && a[i] > a[j]; ) { - double ai = a[i]; a[i] = a[j]; a[j] = ai; - } - } else { // Identify constant sequence - for (double ak = a[k]; ++k < high && ak == a[k]; ); - - if (k < high) { - continue; - } - } - - /* - * Check special cases. - */ - if (run == null) { - if (k == high) { - - /* - * The array is monotonous sequence, - * and therefore already sorted. - */ - return true; - } - - if (k - low < MIN_FIRST_RUN_SIZE) { - - /* - * The first run is too small - * to proceed with scanning. - */ - return false; - } - - run = new int[((size >> 10) | 0x7F) & 0x3FF]; - run[0] = low; - - } else if (a[last - 1] > a[last]) { - - if (count > (k - low) >> MIN_FIRST_RUNS_FACTOR) { - - /* - * The first runs are not long - * enough to continue scanning. - */ - return false; - } - - if (++count == MAX_RUN_CAPACITY) { - - /* - * Array is not highly structured. - */ - return false; - } - - if (count == run.length) { - - /* - * Increase capacity of index array. - */ - run = Arrays.copyOf(run, count << 1); - } - } - run[count] = (last = k); - } - - /* - * Merge runs of highly structured array. - */ - if (count > 1) { - double[] b; int offset = low; - - if (sorter == null || (b = (double[]) sorter.b) == null) { - b = new double[size]; - } else { - offset = sorter.offset; - } - mergeRuns(a, b, offset, 1, sorter != null, run, 0, count); - } - return true; - } - - /** - * Merges the specified runs. - * - * @param a the source array - * @param b the temporary buffer used in merging - * @param offset the start index in the source, inclusive - * @param aim specifies merging: to source ( > 0), buffer ( < 0) or any ( == 0) - * @param parallel indicates whether merging is performed in parallel - * @param run the start indexes of the runs, inclusive - * @param lo the start index of the first run, inclusive - * @param hi the start index of the last run, inclusive - * @return the destination where runs are merged - */ - private static double[] mergeRuns(double[] a, double[] b, int offset, - int aim, boolean parallel, int[] run, int lo, int hi) { - - if (hi - lo == 1) { - if (aim >= 0) { - return a; - } - for (int i = run[hi], j = i - offset, low = run[lo]; i > low; - b[--j] = a[--i] - ); - return b; - } - - /* - * Split into approximately equal parts. - */ - int mi = lo, rmi = (run[lo] + run[hi]) >>> 1; - while (run[++mi + 1] <= rmi); - - /* - * Merge the left and right parts. - */ - double[] a1, a2; - - if (parallel && hi - lo > MIN_RUN_COUNT) { - RunMerger merger = new RunMerger(a, b, offset, 0, run, mi, hi).forkMe(); - a1 = mergeRuns(a, b, offset, -aim, true, run, lo, mi); - a2 = (double[]) merger.getDestination(); - } else { - a1 = mergeRuns(a, b, offset, -aim, false, run, lo, mi); - a2 = mergeRuns(a, b, offset, 0, false, run, mi, hi); - } - - double[] dst = a1 == a ? b : a; - - int k = a1 == a ? run[lo] - offset : run[lo]; - int lo1 = a1 == b ? run[lo] - offset : run[lo]; - int hi1 = a1 == b ? run[mi] - offset : run[mi]; - int lo2 = a2 == b ? run[mi] - offset : run[mi]; - int hi2 = a2 == b ? run[hi] - offset : run[hi]; - - if (parallel) { - new Merger(null, dst, k, a1, lo1, hi1, a2, lo2, hi2).invoke(); - } else { - mergeParts(null, dst, k, a1, lo1, hi1, a2, lo2, hi2); - } - return dst; - } - - /** - * Merges the sorted parts. - * - * @param merger parallel context - * @param dst the destination where parts are merged - * @param k the start index of the destination, inclusive - * @param a1 the first part - * @param lo1 the start index of the first part, inclusive - * @param hi1 the end index of the first part, exclusive - * @param a2 the second part - * @param lo2 the start index of the second part, inclusive - * @param hi2 the end index of the second part, exclusive - */ - private static void mergeParts(Merger merger, double[] dst, int k, - double[] a1, int lo1, int hi1, double[] a2, int lo2, int hi2) { - - if (merger != null && a1 == a2) { - - while (true) { - - /* - * The first part must be larger. - */ - if (hi1 - lo1 < hi2 - lo2) { - int lo = lo1; lo1 = lo2; lo2 = lo; - int hi = hi1; hi1 = hi2; hi2 = hi; - } - - /* - * Small parts will be merged sequentially. - */ - if (hi1 - lo1 < MIN_PARALLEL_MERGE_PARTS_SIZE) { - break; - } - - /* - * Find the median of the larger part. - */ - int mi1 = (lo1 + hi1) >>> 1; - double key = a1[mi1]; - int mi2 = hi2; - - /* - * Partition the smaller part. - */ - for (int loo = lo2; loo < mi2; ) { - int t = (loo + mi2) >>> 1; - - if (key > a2[t]) { - loo = t + 1; - } else { - mi2 = t; - } - } - - int d = mi2 - lo2 + mi1 - lo1; - - /* - * Merge the right sub-parts in parallel. - */ - merger.forkMerger(dst, k + d, a1, mi1, hi1, a2, mi2, hi2); - - /* - * Process the sub-left parts. - */ - hi1 = mi1; - hi2 = mi2; - } - } - - /* - * Merge small parts sequentially. - */ - while (lo1 < hi1 && lo2 < hi2) { - dst[k++] = a1[lo1] < a2[lo2] ? a1[lo1++] : a2[lo2++]; - } - if (dst != a1 || k < lo1) { - while (lo1 < hi1) { - dst[k++] = a1[lo1++]; - } - } - if (dst != a2 || k < lo2) { - while (lo2 < hi2) { - dst[k++] = a2[lo2++]; - } - } - } - -// [class] - - /** - * This class implements parallel sorting. - */ - private static final class Sorter extends CountedCompleter { - private static final long serialVersionUID = 20180818L; - @SuppressWarnings("serial") - private final Object a, b; - private final int low, size, offset, depth; - - private Sorter(CountedCompleter parent, - Object a, Object b, int low, int size, int offset, int depth) { - super(parent); - this.a = a; - this.b = b; - this.low = low; - this.size = size; - this.offset = offset; - this.depth = depth; - } - - @Override - public final void compute() { - if (depth < 0) { - setPendingCount(2); - int half = size >> 1; - new Sorter(this, b, a, low, half, offset, depth + 1).fork(); - new Sorter(this, b, a, low + half, size - half, offset, depth + 1).compute(); - } else { - if (a instanceof int[]) { - sort(this, (int[]) a, depth, low, low + size); - } else if (a instanceof long[]) { - sort(this, (long[]) a, depth, low, low + size); - } else if (a instanceof float[]) { - sort(this, (float[]) a, depth, low, low + size); - } else if (a instanceof double[]) { - sort(this, (double[]) a, depth, low, low + size); - } else { - throw new IllegalArgumentException( - "Unknown type of array: " + a.getClass().getName()); - } - } - tryComplete(); - } - - @Override - public final void onCompletion(CountedCompleter caller) { - if (depth < 0) { - int mi = low + (size >> 1); - boolean src = (depth & 1) == 0; - - new Merger(null, - a, - src ? low : low - offset, - b, - src ? low - offset : low, - src ? mi - offset : mi, - b, - src ? mi - offset : mi, - src ? low + size - offset : low + size - ).invoke(); - } - } - - private void forkSorter(int depth, int low, int high) { - addToPendingCount(1); - Object a = this.a; // Use local variable for performance - new Sorter(this, a, b, low, high - low, offset, depth).fork(); - } - } - - /** - * This class implements parallel merging. - */ - private static final class Merger extends CountedCompleter { - private static final long serialVersionUID = 20180818L; - @SuppressWarnings("serial") - private final Object dst, a1, a2; - private final int k, lo1, hi1, lo2, hi2; - - private Merger(CountedCompleter parent, Object dst, int k, - Object a1, int lo1, int hi1, Object a2, int lo2, int hi2) { - super(parent); - this.dst = dst; - this.k = k; - this.a1 = a1; - this.lo1 = lo1; - this.hi1 = hi1; - this.a2 = a2; - this.lo2 = lo2; - this.hi2 = hi2; - } - - @Override - public final void compute() { - if (dst instanceof int[]) { - mergeParts(this, (int[]) dst, k, - (int[]) a1, lo1, hi1, (int[]) a2, lo2, hi2); - } else if (dst instanceof long[]) { - mergeParts(this, (long[]) dst, k, - (long[]) a1, lo1, hi1, (long[]) a2, lo2, hi2); - } else if (dst instanceof float[]) { - mergeParts(this, (float[]) dst, k, - (float[]) a1, lo1, hi1, (float[]) a2, lo2, hi2); - } else if (dst instanceof double[]) { - mergeParts(this, (double[]) dst, k, - (double[]) a1, lo1, hi1, (double[]) a2, lo2, hi2); - } else { - throw new IllegalArgumentException( - "Unknown type of array: " + dst.getClass().getName()); - } - propagateCompletion(); - } - - private void forkMerger(Object dst, int k, - Object a1, int lo1, int hi1, Object a2, int lo2, int hi2) { - addToPendingCount(1); - new Merger(this, dst, k, a1, lo1, hi1, a2, lo2, hi2).fork(); - } - } - - /** - * This class implements parallel merging of runs. - */ - private static final class RunMerger extends RecursiveTask { - private static final long serialVersionUID = 20180818L; - @SuppressWarnings("serial") - private final Object a, b; - private final int[] run; - private final int offset, aim, lo, hi; - - private RunMerger(Object a, Object b, int offset, - int aim, int[] run, int lo, int hi) { - this.a = a; - this.b = b; - this.offset = offset; - this.aim = aim; - this.run = run; - this.lo = lo; - this.hi = hi; - } - - @Override - protected final Object compute() { - if (a instanceof int[]) { - return mergeRuns((int[]) a, (int[]) b, offset, aim, true, run, lo, hi); - } - if (a instanceof long[]) { - return mergeRuns((long[]) a, (long[]) b, offset, aim, true, run, lo, hi); - } - if (a instanceof float[]) { - return mergeRuns((float[]) a, (float[]) b, offset, aim, true, run, lo, hi); - } - if (a instanceof double[]) { - return mergeRuns((double[]) a, (double[]) b, offset, aim, true, run, lo, hi); - } - throw new IllegalArgumentException( - "Unknown type of array: " + a.getClass().getName()); - } - - private RunMerger forkMe() { - fork(); - return this; - } - - private Object getDestination() { - join(); - return getRawResult(); - } - } -} +/* + * Copyright (c) 2009, 2023, Oracle and/or its affiliates. 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.util; + +import java.util.concurrent.CountedCompleter; +import jdk.internal.misc.Unsafe; + +/** + * This class implements powerful and fully optimized versions, both + * sequential and parallel, of the Dual-Pivot Quicksort algorithm by + * Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch. This algorithm + * offers O(n log(n)) performance on all data sets, and is typically + * faster than traditional (one-pivot) Quicksort implementations. + * + * There are also additional algorithms, invoked from the Dual-Pivot + * Quicksort such as merging sort, sorting network, Radix sort, heap + * sort, mixed (simple, pin, pair) insertion sort, counting sort and + * parallel merge sort. + * + * @author Vladimir Yaroslavskiy + * @author Jon Bentley + * @author Josh Bloch + * @author Doug Lea + * + * @version 2022.06.14 + * + * @since 1.7 * 14 ^ 22 + */ +final class DualPivotQuicksort { + + /** + * Prevents instantiation. + */ + private DualPivotQuicksort() {} + + /* ---------------- Insertion sort section ---------------- */ + + /** + * Max array size to use mixed insertion sort. + */ + private static final int MAX_MIXED_INSERTION_SORT_SIZE = 124; + + /** + * Max array size to use insertion sort. + */ + private static final int MAX_INSERTION_SORT_SIZE = 44; + + /* ----------------- Merging sort section ----------------- */ + + /** + * Min array size to use merging sort. + */ + private static final int MIN_MERGING_SORT_SIZE = 512; + + /** + * Min size of run to continue scanning. + */ + private static final int MIN_RUN_SIZE = 128; + + /* ------------------ Radix sort section ------------------ */ + + /** + * Min array size to use Radix sort. + */ + private static final int MIN_RADIX_SORT_SIZE = 800; + + /* ------------------ Counting sort section --------------- */ + + /** + * Min size of a byte array to use counting sort. + */ + private static final int MIN_BYTE_COUNTING_SORT_SIZE = 36; + + /** + * Min size of a char array to use counting sort. + */ + private static final int MIN_CHAR_COUNTING_SORT_SIZE = 1700; + + /** + * Min size of a short array to use counting sort. + */ + private static final int MIN_SHORT_COUNTING_SORT_SIZE = 2100; + + /* -------------------- Common section -------------------- */ + + /** + * Min array size to perform sorting in parallel. + */ + private static final int MIN_PARALLEL_SORT_SIZE = 1024; + + /** + * Max recursive depth before switching to heap sort. + */ + private static final int MAX_RECURSION_DEPTH = 64 << 1; + + /** + * Max size of additional buffer, + * limited by max_heap / 64 or 2 GB max. + */ + private static final int MAX_BUFFER_SIZE = + (int) Math.min(Runtime.getRuntime().maxMemory() >> 6, Integer.MAX_VALUE); + + /** + * Sorts the specified range of the array using parallel merge + * sort and/or Dual-Pivot Quicksort. + * + * To balance the faster splitting and parallelism of merge sort + * with the faster element partitioning of Quicksort, ranges are + * subdivided in tiers such that, if there is enough parallelism, + * the four-way parallel merge is started, still ensuring enough + * parallelism to process the partitions. + * + * @param a the array to be sorted + * @param parallelism the parallelism level + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void sort(int[] a, int parallelism, int low, int high) { + if (parallelism > 1 && high - low > MIN_PARALLEL_SORT_SIZE) { + new Sorter<>(a, parallelism, low, high - low, 0).invoke(); + } else { + sort(null, a, 0, low, high); + } + } + + /** + * Sorts the specified range of the array using Dual-Pivot Quicksort. + * + * @param sorter parallel context + * @param a the array to be sorted + * @param bits the combination of recursion depth and bit flag, where + * the right bit "0" indicates that range is the leftmost part + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void sort(Sorter sorter, int[] a, int bits, int low, int high) { + while (true) { + int size = high - low; + + /* + * Run adaptive mixed insertion sort on small non-leftmost parts. + */ + if (size < MAX_MIXED_INSERTION_SORT_SIZE + bits && (bits & 1) > 0) { + mixedInsertionSort(a, low, high); + return; + } + + /* + * Invoke insertion sort on small leftmost part. + */ + if (size < MAX_INSERTION_SORT_SIZE) { + insertionSort(a, low, high); + return; + } + + /* + * Try merging sort on large part. + */ + if (size > MIN_MERGING_SORT_SIZE * bits + && tryMergingSort(sorter, a, low, high)) { + return; + } + + /* + * Use an inexpensive approximation of the golden ratio + * to select five sample elements and determine pivots. + */ + int step = (size >> 2) + (size >> 3) + (size >> 8) + 1; + + /* + * Five elements around (and including) the central element + * will be used for pivot selection as described below. The + * unequal choice of spacing these elements was empirically + * determined to work well on a wide variety of inputs. + */ + int end = high - 1; + int e1 = low + step; + int e5 = end - step; + int e3 = (e1 + e5) >>> 1; + int e2 = (e1 + e3) >>> 1; + int e4 = (e3 + e5) >>> 1; + int a3 = a[e3]; + + boolean isRandom = + a[e1] > a[e2] || a[e2] > a3 || a3 > a[e4] || a[e4] > a[e5]; + + /* + * Sort these elements in place by the combination + * of 4-element sorting network and insertion sort. + * + * 1 ------------o-----o------------ + * | | + * 2 ------o-----|-----o-----o------ + * | | | + * 4 ------|-----o-----o-----o------ + * | | + * 5 ------o-----------o------------ + */ + if (a[e2] > a[e5]) { int t = a[e2]; a[e2] = a[e5]; a[e5] = t; } + if (a[e1] > a[e4]) { int t = a[e1]; a[e1] = a[e4]; a[e4] = t; } + 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[e2] > a[e4]) { int t = a[e2]; a[e2] = a[e4]; a[e4] = t; } + + /* + * Insert the third element. + */ + if (a3 < a[e2]) { + if (a3 < a[e1]) { + a[e3] = a[e2]; a[e2] = a[e1]; a[e1] = a3; + } else { + a[e3] = a[e2]; a[e2] = a3; + } + } else if (a3 > a[e4]) { + if (a3 > a[e5]) { + a[e3] = a[e4]; a[e4] = a[e5]; a[e5] = a3; + } else { + a[e3] = a[e4]; a[e4] = a3; + } + } + + /* + * Try Radix sort on large fully random data, + * taking into account parallel context. + */ + isRandom &= a[e1] < a[e2] && a[e2] < a[e3] && a[e3] < a[e4] && a[e4] < a[e5]; + + if (size > MIN_RADIX_SORT_SIZE && isRandom && (sorter == null || bits > 0) + && tryRadixSort(sorter, a, low, high)) { + return; + } + + /* + * Switch to heap sort, if execution time is quadratic. + */ + if ((bits += 2) > MAX_RECURSION_DEPTH) { + heapSort(a, low, high); + return; + } + + // Pointers + int lower = low; // The index of the last element of the left part + int upper = end; // The index of the first element of the right part + + /* + * Partitioning with two pivots on array of fully random elements. + */ + if (a[e1] < a[e2] && a[e2] < a[e3] && a[e3] < a[e4] && a[e4] < a[e5]) { + + /* + * Use the first and fifth of the five sorted elements as + * the pivots. These values are inexpensive approximation + * of tertiles. Note, that pivot1 < pivot2. + */ + int pivot1 = a[e1]; + int pivot2 = a[e5]; + + /* + * The first and the last elements to be sorted are moved + * to the locations formerly occupied by the pivots. When + * partitioning is completed, the pivots are swapped back + * into their final positions, and excluded from the next + * subsequent sorting. + */ + a[e1] = a[lower]; + a[e5] = a[upper]; + + /* + * Skip elements, which are less or greater than the pivots. + */ + while (a[++lower] < pivot1); + while (a[--upper] > pivot2); + + /* + * Backward 3-interval partitioning + * + * left part central part right part + * +------------------------------------------------------------------+ + * | < pivot1 | ? | pivot1 <= && <= pivot2 | > pivot2 | + * +------------------------------------------------------------------+ + * ^ ^ ^ + * | | | + * lower k upper + * + * Pointer k is the last index of ?-part + * Pointer lower is the last index of left part + * Pointer upper is the first index of right part + * + * Invariants: + * + * all in (low, lower] < pivot1 + * all in (k, upper) in [pivot1, pivot2] + * all in [upper, end) > pivot2 + */ + for (int unused = --lower, k = ++upper; --k > lower; ) { + int ak = a[k]; + + if (ak < pivot1) { // Move a[k] to the left side + while (a[++lower] < pivot1) { + if (lower == k) { + break; + } + } + if (a[lower] > pivot2) { + a[k] = a[--upper]; + a[upper] = a[lower]; + } else { + a[k] = a[lower]; + } + a[lower] = ak; + } else if (ak > pivot2) { // Move a[k] to the right side + a[k] = a[--upper]; + a[upper] = ak; + } + } + + /* + * Swap the pivots into their final positions. + */ + a[low] = a[lower]; a[lower] = pivot1; + a[end] = a[upper]; a[upper] = pivot2; + + /* + * Sort non-left parts recursively (possibly in parallel), + * excluding known pivots. + */ + if (size > MIN_PARALLEL_SORT_SIZE && sorter != null) { + sorter.fork(bits | 1, lower + 1, upper); + sorter.fork(bits | 1, upper + 1, high); + } else { + sort(sorter, a, bits | 1, lower + 1, upper); + sort(sorter, a, bits | 1, upper + 1, high); + } + + } else { // Partitioning with one pivot + + /* + * Use the third of the five sorted elements as the pivot. + * This value is inexpensive approximation of the median. + */ + int pivot = a[e3]; + + /* + * The first element to be sorted is moved to the + * location formerly occupied by the pivot. After + * completion of partitioning the pivot is swapped + * back into its final position, and excluded from + * the next subsequent sorting. + */ + a[e3] = a[lower]; + + /* + * Dutch National Flag partitioning + * + * left part central part right part + * +------------------------------------------------------+ + * | < pivot | ? | == pivot | > pivot | + * +------------------------------------------------------+ + * ^ ^ ^ + * | | | + * lower k upper + * + * Pointer k is the last index of ?-part + * Pointer lower is the last index of left part + * Pointer upper is the first index of right part + * + * Invariants: + * + * all in (low, lower] < pivot + * all in (k, upper) == pivot + * all in [upper, end] > pivot + */ + for (int k = ++upper; --k > lower; ) { + int ak = a[k]; + + if (ak != pivot) { + a[k] = pivot; + + if (ak < pivot) { // Move a[k] to the left side + while (a[++lower] < pivot); + + if (a[lower] > pivot) { + a[--upper] = a[lower]; + } + a[lower] = ak; + } else { // ak > pivot - Move a[k] to the right side + a[--upper] = ak; + } + } + } + + /* + * Swap the pivot into its final position. + */ + a[low] = a[lower]; a[lower] = pivot; + + /* + * Sort the right part (possibly in parallel), excluding + * known pivot. All elements from the central part are + * equal and therefore already sorted. + */ + if (size > MIN_PARALLEL_SORT_SIZE && sorter != null) { + sorter.fork(bits | 1, upper, high); + } else { + sort(sorter, a, bits | 1, upper, high); + } + } + high = lower; // Iterate along the left part + } + } + + /** + * Sorts the specified range of the array using mixed insertion sort. + * + * Mixed insertion sort is combination of pin insertion sort, + * simple insertion sort and pair insertion sort. + * + * In the context of Dual-Pivot Quicksort, the pivot element + * from the left part plays the role of sentinel, because it + * is less than any elements from the given part. Therefore, + * expensive check of the left range can be skipped on each + * iteration unless it is the leftmost call. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void mixedInsertionSort(int[] a, int low, int high) { + + /* + * Split part for pin and pair insertion sorts. + */ + int end = high - 3 * ((high - low) >> 3 << 1); + + /* + * Invoke simple insertion sort on small part. + */ + if (end == high) { + for (int i; ++low < high; ) { + int ai = a[i = low]; + + while (ai < a[i - 1]) { + a[i] = a[--i]; + } + a[i] = ai; + } + return; + } + + /* + * Start with pin insertion sort. + */ + for (int i, p = high; ++low < end; ) { + int ai = a[i = low], pin = a[--p]; + + /* + * Swap larger element with pin. + */ + if (ai > pin) { + ai = pin; + a[p] = a[i]; + } + + /* + * Insert element into sorted part. + */ + while (ai < a[i - 1]) { + a[i] = a[--i]; + } + a[i] = ai; + } + + /* + * Finish with pair insertion sort. + */ + for (int i; low < high; ++low) { + int a1 = a[i = low], a2 = a[++low]; + + /* + * Insert two elements per iteration: at first, insert the + * larger element and then insert the smaller element, but + * from the position where the larger element was inserted. + */ + if (a1 > a2) { + + while (a1 < a[--i]) { + a[i + 2] = a[i]; + } + a[++i + 1] = a1; + + while (a2 < a[--i]) { + a[i + 1] = a[i]; + } + a[i + 1] = a2; + + } else if (a1 < a[i - 1]) { + + while (a2 < a[--i]) { + a[i + 2] = a[i]; + } + a[++i + 1] = a2; + + while (a1 < a[--i]) { + a[i + 1] = a[i]; + } + a[i + 1] = a1; + } + } + } + + /** + * Sorts the specified range of the array using insertion sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void insertionSort(int[] a, int low, int high) { + for (int i, k = low; ++k < high; ) { + int ai = a[i = k]; + + if (ai < a[i - 1]) { + do { + a[i] = a[--i]; + } while (i > low && ai < a[i - 1]); + + a[i ] = ai; + } + } + } + + /** + * Tries to sort the specified range of the array using merging sort. + * + * @param sorter parallel context + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + * @return {@code true} if the array is finally sorted, otherwise {@code false} + */ + static boolean tryMergingSort(Sorter sorter, int[] a, int low, int high) { + + /* + * The element run[i] holds the start index + * of i-th sequence in non-descending order. + */ + int count = 1; + int[] run = null; + + /* + * Identify all possible runs. + */ + for (int k = low + 1, last = low; k < high; ) { + + /* + * Find the next run. + */ + if (a[k - 1] < a[k]) { + + // Identify ascending sequence + while (++k < high && a[k - 1] <= a[k]); + + } else if (a[k - 1] > a[k]) { + + // Identify descending sequence + while (++k < high && a[k - 1] >= a[k]); + + // Reverse into ascending order + for (int i = last - 1, j = k; ++i < --j && a[i] > a[j]; ) { + int ai = a[i]; a[i] = a[j]; a[j] = ai; + } + } else { // Identify constant sequence + for (int ak = a[k]; ++k < high && ak == a[k]; ); + + if (k < high) { + continue; + } + } + + /* + * Check if the runs are too + * long to continue scanning. + */ + if (count > 6 && k - low < count * MIN_RUN_SIZE) { + return false; + } + + /* + * Process the run. + */ + if (run == null) { + + if (k == high) { + /* + * Array is monotonous sequence + * and therefore already sorted. + */ + return true; + } + + run = new int[((high - low) >> 9) & 0x1FF | 0x3F]; + run[0] = low; + + } else if (a[last - 1] > a[last]) { // Start the new run + + if (++count == run.length) { + /* + * Array is not highly structured. + */ + return false; + } + } + + /* + * Save the current run. + */ + run[count] = (last = k); + + /* + * Check single-element run at the end. + */ + if (++k == high) { + --k; + } + } + + /* + * Merge all runs. + */ + if (count > 1) { + int[] b; int offset = low; + + if (sorter != null && (b = sorter.b) != null) { + offset = sorter.offset; + } else if ((b = tryAllocate(int[].class, high - low)) == null) { + return false; + } + mergeRuns(a, b, offset, 1, sorter != null, run, 0, count); + } + return true; + } + + /** + * Merges the specified runs. + * + * @param a the source array + * @param b the temporary buffer used in merging + * @param offset the start index in the source, inclusive + * @param aim specifies merging: to source ( > 0), buffer ( < 0) or any ( == 0) + * @param parallel indicates whether merging is performed in parallel + * @param run the start indexes of the runs, inclusive + * @param lo the start index of the first run, inclusive + * @param hi the start index of the last run, inclusive + * @return the destination where runs are merged + */ + private static int[] mergeRuns(int[] a, int[] b, int offset, + int aim, boolean parallel, int[] run, int lo, int hi) { + + if (hi - lo == 1) { + if (aim >= 0) { + return a; + } + System.arraycopy(a, run[lo], b, run[lo] - offset, run[hi] - run[lo]); + return b; + } + + /* + * Split into approximately equal parts. + */ + int mi = lo, rmi = (run[lo] + run[hi]) >>> 1; + while (run[++mi + 1] <= rmi); + + /* + * Merge runs of each part. + */ + int[] a1 = mergeRuns(a, b, offset, -aim, parallel, run, lo, mi); + int[] a2 = mergeRuns(a, b, offset, 0, parallel, run, mi, hi); + int[] dst = a1 == a ? b : a; + + int k = a1 == a ? run[lo] - offset : run[lo]; + int lo1 = a1 == b ? run[lo] - offset : run[lo]; + int hi1 = a1 == b ? run[mi] - offset : run[mi]; + int lo2 = a2 == b ? run[mi] - offset : run[mi]; + int hi2 = a2 == b ? run[hi] - offset : run[hi]; + + /* + * Merge the left and right parts. + */ + if (hi1 - lo1 > MIN_PARALLEL_SORT_SIZE && parallel) { + new Merger<>(null, dst, k, a1, lo1, hi1, a2, lo2, hi2).invoke(); + } else { + mergeParts(null, dst, k, a1, lo1, hi1, a2, lo2, hi2); + } + return dst; + } + + /** + * Merges the sorted parts. + * + * @param merger parallel context + * @param dst the destination where parts are merged + * @param k the start index of the destination, inclusive + * @param a1 the first part + * @param lo1 the start index of the first part, inclusive + * @param hi1 the end index of the first part, exclusive + * @param a2 the second part + * @param lo2 the start index of the second part, inclusive + * @param hi2 the end index of the second part, exclusive + */ + private static void mergeParts(Merger merger, int[] dst, int k, + int[] a1, int lo1, int hi1, int[] a2, int lo2, int hi2) { + + if (merger != null && a1 == a2) { + + while (true) { + + /* + * The first part must be larger. + */ + if (hi1 - lo1 < hi2 - lo2) { + int lo = lo1; lo1 = lo2; lo2 = lo; + int hi = hi1; hi1 = hi2; hi2 = hi; + } + + /* + * Small parts will be merged sequentially. + */ + if (hi1 - lo1 < MIN_PARALLEL_SORT_SIZE) { + break; + } + + /* + * Find the median of the larger part. + */ + int mi1 = (lo1 + hi1) >>> 1; + int key = a1[mi1]; + int mi2 = hi2; + + /* + * Divide the smaller part. + */ + for (int loo = lo2; loo < mi2; ) { + int t = (loo + mi2) >>> 1; + + if (key > a2[t]) { + loo = t + 1; + } else { + mi2 = t; + } + } + + /* + * Reserve space for the left part. + */ + int d = mi2 - lo2 + mi1 - lo1; + + /* + * Merge the right part in parallel. + */ + merger.fork(k + d, mi1, hi1, mi2, hi2); + + /* + * Iterate along the left part. + */ + hi1 = mi1; + hi2 = mi2; + } + } + + /* + * Merge small parts sequentially. + */ + while (lo1 < hi1 && lo2 < hi2) { + dst[k++] = a1[lo1] < a2[lo2] ? a1[lo1++] : a2[lo2++]; + } + if (dst != a1 || k < lo1) { + while (lo1 < hi1) { + dst[k++] = a1[lo1++]; + } + } + if (dst != a2 || k < lo2) { + while (lo2 < hi2) { + dst[k++] = a2[lo2++]; + } + } + } + + /** + * Tries to sort the specified range of the array + * using LSD (The Least Significant Digit) Radix sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + * @return {@code true} if the array is finally sorted, otherwise {@code false} + */ + static boolean tryRadixSort(Sorter sorter, int[] a, int low, int high) { + int[] b; int offset = low, size = high - low; + + /* + * Allocate additional buffer. + */ + if (sorter != null && (b = sorter.b) != null) { + offset = sorter.offset; + } else if ((b = tryAllocate(int[].class, size)) == null) { + return false; + } + + int start = low - offset; + int last = high - offset; + + /* + * Count the number of all digits. + */ + int[] count1 = new int[1024]; + int[] count2 = new int[2048]; + int[] count3 = new int[2048]; + + for (int i = low; i < high; ++i) { + ++count1[ a[i] & 0x3FF]; + ++count2[(a[i] >>> 10) & 0x7FF]; + ++count3[(a[i] >>> 21) ^ 0x400]; // Reverse the sign bit + } + + /* + * Detect digits to be processed. + */ + boolean processDigit1 = processDigit(count1, size, low); + boolean processDigit2 = processDigit(count2, size, low); + boolean processDigit3 = processDigit(count3, size, low); + + /* + * Process the 1-st digit. + */ + if (processDigit1) { + for (int i = high; i > low; ) { + b[--count1[a[--i] & 0x3FF] - offset] = a[i]; + } + } + + /* + * Process the 2-nd digit. + */ + if (processDigit2) { + if (processDigit1) { + for (int i = last; i > start; ) { + a[--count2[(b[--i] >>> 10) & 0x7FF]] = b[i]; + } + } else { + for (int i = high; i > low; ) { + b[--count2[(a[--i] >>> 10) & 0x7FF] - offset] = a[i]; + } + } + } + + /* + * Process the 3-rd digit. + */ + if (processDigit3) { + if (processDigit1 ^ processDigit2) { + for (int i = last; i > start; ) { + a[--count3[(b[--i] >>> 21) ^ 0x400]] = b[i]; + } + } else { + for (int i = high; i > low; ) { + b[--count3[(a[--i] >>> 21) ^ 0x400] - offset] = a[i]; + } + } + } + + /* + * Copy the buffer to original array, if we process ood number of digits. + */ + if (processDigit1 ^ processDigit2 ^ processDigit3) { + System.arraycopy(b, low - offset, a, low, size); + } + return true; + } + + /** + * Checks the count array and then computes the histogram. + * + * @param count the count array + * @param total the total number of elements + * @param low the index of the first element, inclusive + * @return {@code true} if the digit must be processed, otherwise {@code false} + */ + private static boolean processDigit(int[] count, int total, int low) { + + /* + * Check if we can skip given digit. + */ + for (int c : count) { + if (c == total) { + return false; + } + if (c > 0) { + break; + } + } + + /* + * Compute the histogram. + */ + count[0] += low; + + for (int i = 0; ++i < count.length; ) { + count[i] += count[i - 1]; + } + return true; + } + + /** + * Sorts the specified range of the array using heap sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void heapSort(int[] a, int low, int high) { + for (int k = (low + high) >>> 1; k > low; ) { + pushDown(a, --k, a[k], low, high); + } + while (--high > low) { + int max = a[low]; + pushDown(a, low, a[high], low, high); + a[high] = max; + } + } + + /** + * Pushes specified element down during heap sort. + * + * @param a the given array + * @param p the start index + * @param value the given element + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + private static void pushDown(int[] a, int p, int value, int low, int high) { + for (int k ;; a[p] = a[p = k]) { + k = (p << 1) - low + 2; // Index of the right child + + if (k > high) { + break; + } + if (k == high || a[k] < a[k - 1]) { + --k; + } + if (a[k] <= value) { + break; + } + } + a[p] = value; + } + +// #[long] + + /** + * Sorts the specified range of the array using parallel merge + * sort and/or Dual-Pivot Quicksort. + * + * To balance the faster splitting and parallelism of merge sort + * with the faster element partitioning of Quicksort, ranges are + * subdivided in tiers such that, if there is enough parallelism, + * the four-way parallel merge is started, still ensuring enough + * parallelism to process the partitions. + * + * @param a the array to be sorted + * @param parallelism the parallelism level + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void sort(long[] a, int parallelism, int low, int high) { + if (parallelism > 1 && high - low > MIN_PARALLEL_SORT_SIZE) { + new Sorter<>(a, parallelism, low, high - low, 0).invoke(); + } else { + sort(null, a, 0, low, high); + } + } + + /** + * Sorts the specified range of the array using Dual-Pivot Quicksort. + * + * @param sorter parallel context + * @param a the array to be sorted + * @param bits the combination of recursion depth and bit flag, where + * the right bit "0" indicates that range is the leftmost part + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void sort(Sorter sorter, long[] a, int bits, int low, int high) { + while (true) { + int size = high - low; + + /* + * Run adaptive mixed insertion sort on small non-leftmost parts. + */ + if (size < MAX_MIXED_INSERTION_SORT_SIZE + bits && (bits & 1) > 0) { + mixedInsertionSort(a, low, high); + return; + } + + /* + * Invoke insertion sort on small leftmost part. + */ + if (size < MAX_INSERTION_SORT_SIZE) { + insertionSort(a, low, high); + return; + } + + /* + * Try merging sort on large part. + */ + if (size > MIN_MERGING_SORT_SIZE * bits + && tryMergingSort(sorter, a, low, high)) { + return; + } + + /* + * Use an inexpensive approximation of the golden ratio + * to select five sample elements and determine pivots. + */ + int step = (size >> 2) + (size >> 3) + (size >> 8) + 1; + + /* + * Five elements around (and including) the central element + * will be used for pivot selection as described below. The + * unequal choice of spacing these elements was empirically + * determined to work well on a wide variety of inputs. + */ + int end = high - 1; + int e1 = low + step; + int e5 = end - step; + int e3 = (e1 + e5) >>> 1; + int e2 = (e1 + e3) >>> 1; + int e4 = (e3 + e5) >>> 1; + long a3 = a[e3]; + + boolean isRandom = + a[e1] > a[e2] || a[e2] > a3 || a3 > a[e4] || a[e4] > a[e5]; + + /* + * Sort these elements in place by the combination + * of 4-element sorting network and insertion sort. + * + * 1 ------------o-----o------------ + * | | + * 2 ------o-----|-----o-----o------ + * | | | + * 4 ------|-----o-----o-----o------ + * | | + * 5 ------o-----------o------------ + */ + if (a[e2] > a[e5]) { long t = a[e2]; a[e2] = a[e5]; a[e5] = t; } + if (a[e1] > a[e4]) { long t = a[e1]; a[e1] = a[e4]; a[e4] = t; } + 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[e2] > a[e4]) { long t = a[e2]; a[e2] = a[e4]; a[e4] = t; } + + /* + * Insert the third element. + */ + if (a3 < a[e2]) { + if (a3 < a[e1]) { + a[e3] = a[e2]; a[e2] = a[e1]; a[e1] = a3; + } else { + a[e3] = a[e2]; a[e2] = a3; + } + } else if (a3 > a[e4]) { + if (a3 > a[e5]) { + a[e3] = a[e4]; a[e4] = a[e5]; a[e5] = a3; + } else { + a[e3] = a[e4]; a[e4] = a3; + } + } + + /* + * Try Radix sort on large fully random data, + * taking into account parallel context. + */ + isRandom &= a[e1] < a[e2] && a[e2] < a[e3] && a[e3] < a[e4] && a[e4] < a[e5]; + + if (size > MIN_RADIX_SORT_SIZE && isRandom && (sorter == null || bits > 0) + && tryRadixSort(sorter, a, low, high)) { + return; + } + + /* + * Switch to heap sort, if execution time is quadratic. + */ + if ((bits += 2) > MAX_RECURSION_DEPTH) { + heapSort(a, low, high); + return; + } + + // Pointers + int lower = low; // The index of the last element of the left part + int upper = end; // The index of the first element of the right part + + /* + * Partitioning with two pivots on array of fully random elements. + */ + if (a[e1] < a[e2] && a[e2] < a[e3] && a[e3] < a[e4] && a[e4] < a[e5]) { + + /* + * Use the first and fifth of the five sorted elements as + * the pivots. These values are inexpensive approximation + * of tertiles. Note, that pivot1 < pivot2. + */ + long pivot1 = a[e1]; + long pivot2 = a[e5]; + + /* + * The first and the last elements to be sorted are moved + * to the locations formerly occupied by the pivots. When + * partitioning is completed, the pivots are swapped back + * into their final positions, and excluded from the next + * subsequent sorting. + */ + a[e1] = a[lower]; + a[e5] = a[upper]; + + /* + * Skip elements, which are less or greater than the pivots. + */ + while (a[++lower] < pivot1); + while (a[--upper] > pivot2); + + /* + * Backward 3-interval partitioning + * + * left part central part right part + * +------------------------------------------------------------------+ + * | < pivot1 | ? | pivot1 <= && <= pivot2 | > pivot2 | + * +------------------------------------------------------------------+ + * ^ ^ ^ + * | | | + * lower k upper + * + * Pointer k is the last index of ?-part + * Pointer lower is the last index of left part + * Pointer upper is the first index of right part + * + * Invariants: + * + * all in (low, lower] < pivot1 + * all in (k, upper) in [pivot1, pivot2] + * all in [upper, end) > pivot2 + */ + for (int unused = --lower, k = ++upper; --k > lower; ) { + long ak = a[k]; + + if (ak < pivot1) { // Move a[k] to the left side + while (a[++lower] < pivot1) { + if (lower == k) { + break; + } + } + if (a[lower] > pivot2) { + a[k] = a[--upper]; + a[upper] = a[lower]; + } else { + a[k] = a[lower]; + } + a[lower] = ak; + } else if (ak > pivot2) { // Move a[k] to the right side + a[k] = a[--upper]; + a[upper] = ak; + } + } + + /* + * Swap the pivots into their final positions. + */ + a[low] = a[lower]; a[lower] = pivot1; + a[end] = a[upper]; a[upper] = pivot2; + + /* + * Sort non-left parts recursively (possibly in parallel), + * excluding known pivots. + */ + if (size > MIN_PARALLEL_SORT_SIZE && sorter != null) { + sorter.fork(bits | 1, lower + 1, upper); + sorter.fork(bits | 1, upper + 1, high); + } else { + sort(sorter, a, bits | 1, lower + 1, upper); + sort(sorter, a, bits | 1, upper + 1, high); + } + + } else { // Partitioning with one pivot + + /* + * Use the third of the five sorted elements as the pivot. + * This value is inexpensive approximation of the median. + */ + long pivot = a[e3]; + + /* + * The first element to be sorted is moved to the + * location formerly occupied by the pivot. After + * completion of partitioning the pivot is swapped + * back into its final position, and excluded from + * the next subsequent sorting. + */ + a[e3] = a[lower]; + + /* + * Dutch National Flag partitioning + * + * left part central part right part + * +------------------------------------------------------+ + * | < pivot | ? | == pivot | > pivot | + * +------------------------------------------------------+ + * ^ ^ ^ + * | | | + * lower k upper + * + * Pointer k is the last index of ?-part + * Pointer lower is the last index of left part + * Pointer upper is the first index of right part + * + * Invariants: + * + * all in (low, lower] < pivot + * all in (k, upper) == pivot + * all in [upper, end] > pivot + */ + for (int k = ++upper; --k > lower; ) { + long ak = a[k]; + + if (ak != pivot) { + a[k] = pivot; + + if (ak < pivot) { // Move a[k] to the left side + while (a[++lower] < pivot); + + if (a[lower] > pivot) { + a[--upper] = a[lower]; + } + a[lower] = ak; + } else { // ak > pivot - Move a[k] to the right side + a[--upper] = ak; + } + } + } + + /* + * Swap the pivot into its final position. + */ + a[low] = a[lower]; a[lower] = pivot; + + /* + * Sort the right part (possibly in parallel), excluding + * known pivot. All elements from the central part are + * equal and therefore already sorted. + */ + if (size > MIN_PARALLEL_SORT_SIZE && sorter != null) { + sorter.fork(bits | 1, upper, high); + } else { + sort(sorter, a, bits | 1, upper, high); + } + } + high = lower; // Iterate along the left part + } + } + + /** + * Sorts the specified range of the array using mixed insertion sort. + * + * Mixed insertion sort is combination of pin insertion sort, + * simple insertion sort and pair insertion sort. + * + * In the context of Dual-Pivot Quicksort, the pivot element + * from the left part plays the role of sentinel, because it + * is less than any elements from the given part. Therefore, + * expensive check of the left range can be skipped on each + * iteration unless it is the leftmost call. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void mixedInsertionSort(long[] a, int low, int high) { + + /* + * Split part for pin and pair insertion sorts. + */ + int end = high - 3 * ((high - low) >> 3 << 1); + + /* + * Invoke simple insertion sort on small part. + */ + if (end == high) { + for (int i; ++low < high; ) { + long ai = a[i = low]; + + while (ai < a[i - 1]) { + a[i] = a[--i]; + } + a[i] = ai; + } + return; + } + + /* + * Start with pin insertion sort. + */ + for (int i, p = high; ++low < end; ) { + long ai = a[i = low], pin = a[--p]; + + /* + * Swap larger element with pin. + */ + if (ai > pin) { + ai = pin; + a[p] = a[i]; + } + + /* + * Insert element into sorted part. + */ + while (ai < a[i - 1]) { + a[i] = a[--i]; + } + a[i] = ai; + } + + /* + * Finish with pair insertion sort. + */ + for (int i; low < high; ++low) { + long a1 = a[i = low], a2 = a[++low]; + + /* + * Insert two elements per iteration: at first, insert the + * larger element and then insert the smaller element, but + * from the position where the larger element was inserted. + */ + if (a1 > a2) { + + while (a1 < a[--i]) { + a[i + 2] = a[i]; + } + a[++i + 1] = a1; + + while (a2 < a[--i]) { + a[i + 1] = a[i]; + } + a[i + 1] = a2; + + } else if (a1 < a[i - 1]) { + + while (a2 < a[--i]) { + a[i + 2] = a[i]; + } + a[++i + 1] = a2; + + while (a1 < a[--i]) { + a[i + 1] = a[i]; + } + a[i + 1] = a1; + } + } + } + + /** + * Sorts the specified range of the array using insertion sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void insertionSort(long[] a, int low, int high) { + for (int i, k = low; ++k < high; ) { + long ai = a[i = k]; + + if (ai < a[i - 1]) { + do { + a[i] = a[--i]; + } while (i > low && ai < a[i - 1]); + + a[i ] = ai; + } + } + } + + /** + * Tries to sort the specified range of the array using merging sort. + * + * @param sorter parallel context + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + * @return {@code true} if the array is finally sorted, otherwise {@code false} + */ + static boolean tryMergingSort(Sorter sorter, long[] a, int low, int high) { + + /* + * The element run[i] holds the start index + * of i-th sequence in non-descending order. + */ + int count = 1; + int[] run = null; + + /* + * Identify all possible runs. + */ + for (int k = low + 1, last = low; k < high; ) { + + /* + * Find the next run. + */ + if (a[k - 1] < a[k]) { + + // Identify ascending sequence + while (++k < high && a[k - 1] <= a[k]); + + } else if (a[k - 1] > a[k]) { + + // Identify descending sequence + while (++k < high && a[k - 1] >= a[k]); + + // Reverse into ascending order + for (int i = last - 1, j = k; ++i < --j && a[i] > a[j]; ) { + long ai = a[i]; a[i] = a[j]; a[j] = ai; + } + } else { // Identify constant sequence + for (long ak = a[k]; ++k < high && ak == a[k]; ); + + if (k < high) { + continue; + } + } + + /* + * Check if the runs are too + * long to continue scanning. + */ + if (count > 6 && k - low < count * MIN_RUN_SIZE) { + return false; + } + + /* + * Process the run. + */ + if (run == null) { + + if (k == high) { + /* + * Array is monotonous sequence + * and therefore already sorted. + */ + return true; + } + + run = new int[((high - low) >> 9) & 0x1FF | 0x3F]; + run[0] = low; + + } else if (a[last - 1] > a[last]) { // Start the new run + + if (++count == run.length) { + /* + * Array is not highly structured. + */ + return false; + } + } + + /* + * Save the current run. + */ + run[count] = (last = k); + + /* + * Check single-element run at the end. + */ + if (++k == high) { + --k; + } + } + + /* + * Merge all runs. + */ + if (count > 1) { + long[] b; int offset = low; + + if (sorter != null && (b = sorter.b) != null) { + offset = sorter.offset; + } else if ((b = tryAllocate(long[].class, high - low)) == null) { + return false; + } + mergeRuns(a, b, offset, 1, sorter != null, run, 0, count); + } + return true; + } + + /** + * Merges the specified runs. + * + * @param a the source array + * @param b the temporary buffer used in merging + * @param offset the start index in the source, inclusive + * @param aim specifies merging: to source ( > 0), buffer ( < 0) or any ( == 0) + * @param parallel indicates whether merging is performed in parallel + * @param run the start indexes of the runs, inclusive + * @param lo the start index of the first run, inclusive + * @param hi the start index of the last run, inclusive + * @return the destination where runs are merged + */ + private static long[] mergeRuns(long[] a, long[] b, int offset, + int aim, boolean parallel, int[] run, int lo, int hi) { + + if (hi - lo == 1) { + if (aim >= 0) { + return a; + } + System.arraycopy(a, run[lo], b, run[lo] - offset, run[hi] - run[lo]); + return b; + } + + /* + * Split into approximately equal parts. + */ + int mi = lo, rmi = (run[lo] + run[hi]) >>> 1; + while (run[++mi + 1] <= rmi); + + /* + * Merge runs of each part. + */ + long[] a1 = mergeRuns(a, b, offset, -aim, parallel, run, lo, mi); + long[] a2 = mergeRuns(a, b, offset, 0, parallel, run, mi, hi); + long[] dst = a1 == a ? b : a; + + int k = a1 == a ? run[lo] - offset : run[lo]; + int lo1 = a1 == b ? run[lo] - offset : run[lo]; + int hi1 = a1 == b ? run[mi] - offset : run[mi]; + int lo2 = a2 == b ? run[mi] - offset : run[mi]; + int hi2 = a2 == b ? run[hi] - offset : run[hi]; + + /* + * Merge the left and right parts. + */ + if (hi1 - lo1 > MIN_PARALLEL_SORT_SIZE && parallel) { + new Merger<>(null, dst, k, a1, lo1, hi1, a2, lo2, hi2).invoke(); + } else { + mergeParts(null, dst, k, a1, lo1, hi1, a2, lo2, hi2); + } + return dst; + } + + /** + * Merges the sorted parts. + * + * @param merger parallel context + * @param dst the destination where parts are merged + * @param k the start index of the destination, inclusive + * @param a1 the first part + * @param lo1 the start index of the first part, inclusive + * @param hi1 the end index of the first part, exclusive + * @param a2 the second part + * @param lo2 the start index of the second part, inclusive + * @param hi2 the end index of the second part, exclusive + */ + private static void mergeParts(Merger merger, long[] dst, int k, + long[] a1, int lo1, int hi1, long[] a2, int lo2, int hi2) { + + if (merger != null && a1 == a2) { + + while (true) { + + /* + * The first part must be larger. + */ + if (hi1 - lo1 < hi2 - lo2) { + int lo = lo1; lo1 = lo2; lo2 = lo; + int hi = hi1; hi1 = hi2; hi2 = hi; + } + + /* + * Small parts will be merged sequentially. + */ + if (hi1 - lo1 < MIN_PARALLEL_SORT_SIZE) { + break; + } + + /* + * Find the median of the larger part. + */ + int mi1 = (lo1 + hi1) >>> 1; + long key = a1[mi1]; + int mi2 = hi2; + + /* + * Divide the smaller part. + */ + for (int loo = lo2; loo < mi2; ) { + int t = (loo + mi2) >>> 1; + + if (key > a2[t]) { + loo = t + 1; + } else { + mi2 = t; + } + } + + /* + * Reserve space for the left part. + */ + int d = mi2 - lo2 + mi1 - lo1; + + /* + * Merge the right part in parallel. + */ + merger.fork(k + d, mi1, hi1, mi2, hi2); + + /* + * Iterate along the left part. + */ + hi1 = mi1; + hi2 = mi2; + } + } + + /* + * Merge small parts sequentially. + */ + while (lo1 < hi1 && lo2 < hi2) { + dst[k++] = a1[lo1] < a2[lo2] ? a1[lo1++] : a2[lo2++]; + } + if (dst != a1 || k < lo1) { + while (lo1 < hi1) { + dst[k++] = a1[lo1++]; + } + } + if (dst != a2 || k < lo2) { + while (lo2 < hi2) { + dst[k++] = a2[lo2++]; + } + } + } + + /** + * Tries to sort the specified range of the array + * using LSD (The Least Significant Digit) Radix sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + * @return {@code true} if the array is finally sorted, otherwise {@code false} + */ + static boolean tryRadixSort(Sorter sorter, long[] a, int low, int high) { + long[] b; int offset = low, size = high - low; + + /* + * Allocate additional buffer. + */ + if (sorter != null && (b = sorter.b) != null) { + offset = sorter.offset; + } else if ((b = tryAllocate(long[].class, size)) == null) { + return false; + } + + int start = low - offset; + int last = high - offset; + + /* + * Count the number of all digits. + */ + int[] count1 = new int[1024]; + int[] count2 = new int[2048]; + int[] count3 = new int[2048]; + int[] count4 = new int[2048]; + int[] count5 = new int[2048]; + int[] count6 = new int[1024]; + + for (int i = low; i < high; ++i) { + ++count1[(int) (a[i] & 0x3FF)]; + ++count2[(int) ((a[i] >>> 10) & 0x7FF)]; + ++count3[(int) ((a[i] >>> 21) & 0x7FF)]; + ++count4[(int) ((a[i] >>> 32) & 0x7FF)]; + ++count5[(int) ((a[i] >>> 43) & 0x7FF)]; + ++count6[(int) ((a[i] >>> 54) ^ 0x200)]; // Reverse the sign bit + } + + /* + * Detect digits to be processed. + */ + boolean processDigit1 = processDigit(count1, size, low); + boolean processDigit2 = processDigit(count2, size, low); + boolean processDigit3 = processDigit(count3, size, low); + boolean processDigit4 = processDigit(count4, size, low); + boolean processDigit5 = processDigit(count5, size, low); + boolean processDigit6 = processDigit(count6, size, low); + + /* + * Process the 1-st digit. + */ + if (processDigit1) { + for (int i = high; i > low; ) { + b[--count1[(int) (a[--i] & 0x3FF)] - offset] = a[i]; + } + } + + /* + * Process the 2-nd digit. + */ + if (processDigit2) { + if (processDigit1) { + for (int i = last; i > start; ) { + a[--count2[(int) ((b[--i] >>> 10) & 0x7FF)]] = b[i]; + } + } else { + for (int i = high; i > low; ) { + b[--count2[(int) ((a[--i] >>> 10) & 0x7FF)] - offset] = a[i]; + } + } + } + + /* + * Process the 3-rd digit. + */ + if (processDigit3) { + if (processDigit1 ^ processDigit2) { + for (int i = last; i > start; ) { + a[--count3[(int) ((b[--i] >>> 21) & 0x7FF)]] = b[i]; + } + } else { + for (int i = high; i > low; ) { + b[--count3[(int) ((a[--i] >>> 21) & 0x7FF)] - offset] = a[i]; + } + } + } + + /* + * Process the 4-th digit. + */ + if (processDigit4) { + if (processDigit1 ^ processDigit2 ^ processDigit3) { + for (int i = last; i > start; ) { + a[--count4[(int) ((b[--i] >>> 32) & 0x7FF)]] = b[i]; + } + } else { + for (int i = high; i > low; ) { + b[--count4[(int) ((a[--i] >>> 32) & 0x7FF)] - offset] = a[i]; + } + } + } + + /* + * Process the 5-th digit. + */ + if (processDigit5) { + if (processDigit1 ^ processDigit2 ^ processDigit3 ^ processDigit4) { + for (int i = last; i > start; ) { + a[--count5[(int) ((b[--i] >>> 43) & 0x7FF)]] = b[i]; + } + } else { + for (int i = high; i > low; ) { + b[--count5[(int) ((a[--i] >>> 43) & 0x7FF)] - offset] = a[i]; + } + } + } + + /* + * Process the 6-th digit. + */ + if (processDigit6) { + if (processDigit1 ^ processDigit2 ^ processDigit3 ^ processDigit4 ^ processDigit5) { + for (int i = last; i > start; ) { + a[--count6[(int) ((b[--i] >>> 54) ^ 0x200)]] = b[i]; + } + } else { + for (int i = high; i > low; ) { + b[--count6[(int) ((a[--i] >>> 54) ^ 0x200)] - offset] = a[i]; + } + } + } + + /* + * Copy the buffer to original array, if we process ood number of digits. + */ + if (processDigit1 ^ processDigit2 ^ processDigit3 ^ processDigit4 ^ processDigit5 ^ processDigit6) { + System.arraycopy(b, low - offset, a, low, size); + } + return true; + } + + /** + * Sorts the specified range of the array using heap sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void heapSort(long[] a, int low, int high) { + for (int k = (low + high) >>> 1; k > low; ) { + pushDown(a, --k, a[k], low, high); + } + while (--high > low) { + long max = a[low]; + pushDown(a, low, a[high], low, high); + a[high] = max; + } + } + + /** + * Pushes specified element down during heap sort. + * + * @param a the given array + * @param p the start index + * @param value the given element + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + private static void pushDown(long[] a, int p, long value, int low, int high) { + for (int k ;; a[p] = a[p = k]) { + k = (p << 1) - low + 2; // Index of the right child + + if (k > high) { + break; + } + if (k == high || a[k] < a[k - 1]) { + --k; + } + if (a[k] <= value) { + break; + } + } + a[p] = value; + } + +// #[byte] + + /** + * Sorts the specified range of the array using + * counting sort or insertion sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void sort(byte[] a, int low, int high) { + if (high - low > MIN_BYTE_COUNTING_SORT_SIZE) { + countingSort(a, low, high); + } else { + insertionSort(a, low, high); + } + } + + /** + * The number of distinct byte values. + */ + private static final int NUM_BYTE_VALUES = 1 << 8; + + /** + * Sorts the specified range of the array using counting sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + private static void countingSort(byte[] a, int low, int high) { + int[] count = new int[NUM_BYTE_VALUES]; + + /* + * Compute the histogram. + */ + for (int i = high; i > low; ++count[a[--i] & 0xFF]); + + /* + * Put values on their final positions. + */ + for (int i = Byte.MAX_VALUE + 1; high > low; ) { + while (count[--i & 0xFF] == 0); + + int num = count[i & 0xFF]; + + do { + a[--high] = (byte) i; + } while (--num > 0); + } + } + + /** + * Sorts the specified range of the array using insertion sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void insertionSort(byte[] a, int low, int high) { + for (int i, k = low; ++k < high; ) { + byte ai = a[i = k]; + + if (ai < a[i - 1]) { + do { + a[i] = a[--i]; + } while (i > low && ai < a[i - 1]); + + a[i ] = ai; + } + } + } + +// #[char] + + /** + * Sorts the specified range of the array using + * counting sort or Dual-Pivot Quicksort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void sort(char[] a, int low, int high) { + if (high - low > MIN_CHAR_COUNTING_SORT_SIZE) { + countingSort(a, low, high); + } else { + sort(a, 0, low, high); + } + } + + /** + * The number of distinct char values. + */ + private static final int NUM_CHAR_VALUES = 1 << 16; + + /** + * Sorts the specified range of the array using counting sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + private static void countingSort(char[] a, int low, int high) { + int[] count = new int[NUM_CHAR_VALUES]; + + /* + * Compute the histogram. + */ + for (int i = high; i > low; ++count[a[--i]]); + + /* + * Put values on their final positions. + */ + if (high - low > NUM_CHAR_VALUES) { + for (int i = NUM_CHAR_VALUES; i > 0; ) { + for (low = high - count[--i]; high > low; ) { + a[--high] = (char) i; + } + } + } else { + for (int i = NUM_CHAR_VALUES; high > low; ) { + while (count[--i] == 0); + + int num = count[i]; + + do { + a[--high] = (char) i; + } while (--num > 0); + } + } + } + + /** + * Sorts the specified range of the array using Dual-Pivot Quicksort. + * + * @param a the array to be sorted + * @param bits the combination of recursion depth and bit flag, where + * the right bit "0" indicates that range is the leftmost part + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void sort(char[] a, int bits, int low, int high) { + while (true) { + int size = high - low; + + /* + * Invoke insertion sort on small part. + */ + if (size < MAX_INSERTION_SORT_SIZE) { + insertionSort(a, low, high); + return; + } + + /* + * Switch to counting sort, if execution time is quadratic. + */ + if ((bits += 2) > MAX_RECURSION_DEPTH) { + countingSort(a, low, high); + return; + } + + /* + * Use an inexpensive approximation of the golden ratio + * to select five sample elements and determine pivots. + */ + int step = (size >> 2) + (size >> 3) + (size >> 8) + 1; + + /* + * Five elements around (and including) the central element + * will be used for pivot selection as described below. The + * unequal choice of spacing these elements was empirically + * determined to work well on a wide variety of inputs. + */ + int end = high - 1; + int e1 = low + step; + int e5 = end - step; + int e3 = (e1 + e5) >>> 1; + int e2 = (e1 + e3) >>> 1; + int e4 = (e3 + e5) >>> 1; + char a3 = a[e3]; + + /* + * Sort these elements in place by the combination + * of 4-element sorting network and insertion sort. + * + * 1 ------------o-----o------------ + * | | + * 2 ------o-----|-----o-----o------ + * | | | + * 4 ------|-----o-----o-----o------ + * | | + * 5 ------o-----------o------------ + */ + if (a[e2] > a[e5]) { char t = a[e2]; a[e2] = a[e5]; a[e5] = t; } + if (a[e1] > a[e4]) { char t = a[e1]; a[e1] = a[e4]; a[e4] = t; } + 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[e2] > a[e4]) { char t = a[e2]; a[e2] = a[e4]; a[e4] = t; } + + /* + * Insert the third element. + */ + if (a3 < a[e2]) { + if (a3 < a[e1]) { + a[e3] = a[e2]; a[e2] = a[e1]; a[e1] = a3; + } else { + a[e3] = a[e2]; a[e2] = a3; + } + } else if (a3 > a[e4]) { + if (a3 > a[e5]) { + a[e3] = a[e4]; a[e4] = a[e5]; a[e5] = a3; + } else { + a[e3] = a[e4]; a[e4] = a3; + } + } + + // Pointers + int lower = low; // The index of the last element of the left part + int upper = end; // The index of the first element of the right part + + /* + * Partitioning with two pivots on array of fully random elements. + */ + if (a[e1] < a[e2] && a[e2] < a[e3] && a[e3] < a[e4] && a[e4] < a[e5]) { + + /* + * Use the first and fifth of the five sorted elements as + * the pivots. These values are inexpensive approximation + * of tertiles. Note, that pivot1 < pivot2. + */ + char pivot1 = a[e1]; + char pivot2 = a[e5]; + + /* + * The first and the last elements to be sorted are moved + * to the locations formerly occupied by the pivots. When + * partitioning is completed, the pivots are swapped back + * into their final positions, and excluded from the next + * subsequent sorting. + */ + a[e1] = a[lower]; + a[e5] = a[upper]; + + /* + * Skip elements, which are less or greater than the pivots. + */ + while (a[++lower] < pivot1); + while (a[--upper] > pivot2); + + /* + * Backward 3-interval partitioning + * + * left part central part right part + * +------------------------------------------------------------------+ + * | < pivot1 | ? | pivot1 <= && <= pivot2 | > pivot2 | + * +------------------------------------------------------------------+ + * ^ ^ ^ + * | | | + * lower k upper + * + * Pointer k is the last index of ?-part + * Pointer lower is the last index of left part + * Pointer upper is the first index of right part + * + * Invariants: + * + * all in (low, lower] < pivot1 + * all in (k, upper) in [pivot1, pivot2] + * all in [upper, end) > pivot2 + */ + for (int unused = --lower, k = ++upper; --k > lower; ) { + char ak = a[k]; + + if (ak < pivot1) { // Move a[k] to the left side + while (a[++lower] < pivot1) { + if (lower == k) { + break; + } + } + if (a[lower] > pivot2) { + a[k] = a[--upper]; + a[upper] = a[lower]; + } else { + a[k] = a[lower]; + } + a[lower] = ak; + } else if (ak > pivot2) { // Move a[k] to the right side + a[k] = a[--upper]; + a[upper] = ak; + } + } + + /* + * Swap the pivots into their final positions. + */ + a[low] = a[lower]; a[lower] = pivot1; + a[end] = a[upper]; a[upper] = pivot2; + + /* + * Sort non-left parts recursively, + * excluding known pivots. + */ + sort(a, bits | 1, lower + 1, upper); + sort(a, bits | 1, upper + 1, high); + + } else { // Partitioning with one pivot + + /* + * Use the third of the five sorted elements as the pivot. + * This value is inexpensive approximation of the median. + */ + char pivot = a[e3]; + + /* + * The first element to be sorted is moved to the + * location formerly occupied by the pivot. After + * completion of partitioning the pivot is swapped + * back into its final position, and excluded from + * the next subsequent sorting. + */ + a[e3] = a[lower]; + + /* + * Dutch National Flag partitioning + * + * left part central part right part + * +------------------------------------------------------+ + * | < pivot | ? | == pivot | > pivot | + * +------------------------------------------------------+ + * ^ ^ ^ + * | | | + * lower k upper + * + * Pointer k is the last index of ?-part + * Pointer lower is the last index of left part + * Pointer upper is the first index of right part + * + * Invariants: + * + * all in (low, lower] < pivot + * all in (k, upper) == pivot + * all in [upper, end] > pivot + */ + for (int k = ++upper; --k > lower; ) { + char ak = a[k]; + + if (ak != pivot) { + a[k] = pivot; + + if (ak < pivot) { // Move a[k] to the left side + while (a[++lower] < pivot); + + if (a[lower] > pivot) { + a[--upper] = a[lower]; + } + a[lower] = ak; + } else { // ak > pivot - Move a[k] to the right side + a[--upper] = ak; + } + } + } + + /* + * Swap the pivot into its final position. + */ + a[low] = a[lower]; a[lower] = pivot; + + /* + * Sort the right part, excluding known pivot. + * All elements from the central part are + * equal and therefore already sorted. + */ + sort(a, bits | 1, upper, high); + } + high = lower; // Iterate along the left part + } + } + + /** + * Sorts the specified range of the array using insertion sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void insertionSort(char[] a, int low, int high) { + for (int i, k = low; ++k < high; ) { + char ai = a[i = k]; + + if (ai < a[i - 1]) { + do { + a[i] = a[--i]; + } while (i > low && ai < a[i - 1]); + + a[i ] = ai; + } + } + } + +// #[short] + + /** + * Sorts the specified range of the array using + * counting sort or Dual-Pivot Quicksort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void sort(short[] a, int low, int high) { + if (high - low > MIN_SHORT_COUNTING_SORT_SIZE) { + countingSort(a, low, high); + } else { + sort(a, 0, low, high); + } + } + + /** + * The number of distinct short values. + */ + private static final int NUM_SHORT_VALUES = 1 << 16; + + /** + * Sorts the specified range of the array using counting sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + private static void countingSort(short[] a, int low, int high) { + int[] count = new int[NUM_SHORT_VALUES]; + + /* + * Compute the histogram. + */ + for (int i = high; i > low; ++count[a[--i] & 0xFFFF]); + + /* + * Place values on their final positions. + */ + if (high - low > NUM_SHORT_VALUES) { + for (int i = Short.MAX_VALUE; i >= Short.MIN_VALUE; --i) { + for (low = high - count[i & 0xFFFF]; high > low; + a[--high] = (short) i + ); + } + } else { + for (int i = Short.MAX_VALUE + 1; high > low; ) { + while (count[--i & 0xFFFF] == 0); + + int num = count[i & 0xFFFF]; + + do { + a[--high] = (short) i; + } while (--num > 0); + } + } + } + + /** + * Sorts the specified range of the array using Dual-Pivot Quicksort. + * + * @param a the array to be sorted + * @param bits the combination of recursion depth and bit flag, where + * the right bit "0" indicates that range is the leftmost part + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void sort(short[] a, int bits, int low, int high) { + while (true) { + int size = high - low; + + /* + * Invoke insertion sort on small part. + */ + if (size < MAX_INSERTION_SORT_SIZE) { + insertionSort(a, low, high); + return; + } + + /* + * Switch to counting sort, if execution time is quadratic. + */ + if ((bits += 2) > MAX_RECURSION_DEPTH) { + countingSort(a, low, high); + return; + } + + /* + * Use an inexpensive approximation of the golden ratio + * to select five sample elements and determine pivots. + */ + int step = (size >> 2) + (size >> 3) + (size >> 8) + 1; + + /* + * Five elements around (and including) the central element + * will be used for pivot selection as described below. The + * unequal choice of spacing these elements was empirically + * determined to work well on a wide variety of inputs. + */ + int end = high - 1; + int e1 = low + step; + int e5 = end - step; + int e3 = (e1 + e5) >>> 1; + int e2 = (e1 + e3) >>> 1; + int e4 = (e3 + e5) >>> 1; + short a3 = a[e3]; + + /* + * Sort these elements in place by the combination + * of 4-element sorting network and insertion sort. + * + * 1 ------------o-----o------------ + * | | + * 2 ------o-----|-----o-----o------ + * | | | + * 4 ------|-----o-----o-----o------ + * | | + * 5 ------o-----------o------------ + */ + if (a[e2] > a[e5]) { short t = a[e2]; a[e2] = a[e5]; a[e5] = t; } + if (a[e1] > a[e4]) { short t = a[e1]; a[e1] = a[e4]; a[e4] = t; } + 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[e2] > a[e4]) { short t = a[e2]; a[e2] = a[e4]; a[e4] = t; } + + /* + * Insert the third element. + */ + if (a3 < a[e2]) { + if (a3 < a[e1]) { + a[e3] = a[e2]; a[e2] = a[e1]; a[e1] = a3; + } else { + a[e3] = a[e2]; a[e2] = a3; + } + } else if (a3 > a[e4]) { + if (a3 > a[e5]) { + a[e3] = a[e4]; a[e4] = a[e5]; a[e5] = a3; + } else { + a[e3] = a[e4]; a[e4] = a3; + } + } + + // Pointers + int lower = low; // The index of the last element of the left part + int upper = end; // The index of the first element of the right part + + /* + * Partitioning with two pivots on array of fully random elements. + */ + if (a[e1] < a[e2] && a[e2] < a[e3] && a[e3] < a[e4] && a[e4] < a[e5]) { + + /* + * Use the first and fifth of the five sorted elements as + * the pivots. These values are inexpensive approximation + * of tertiles. Note, that pivot1 < pivot2. + */ + short pivot1 = a[e1]; + short pivot2 = a[e5]; + + /* + * The first and the last elements to be sorted are moved + * to the locations formerly occupied by the pivots. When + * partitioning is completed, the pivots are swapped back + * into their final positions, and excluded from the next + * subsequent sorting. + */ + a[e1] = a[lower]; + a[e5] = a[upper]; + + /* + * Skip elements, which are less or greater than the pivots. + */ + while (a[++lower] < pivot1); + while (a[--upper] > pivot2); + + /* + * Backward 3-interval partitioning + * + * left part central part right part + * +------------------------------------------------------------------+ + * | < pivot1 | ? | pivot1 <= && <= pivot2 | > pivot2 | + * +------------------------------------------------------------------+ + * ^ ^ ^ + * | | | + * lower k upper + * + * Pointer k is the last index of ?-part + * Pointer lower is the last index of left part + * Pointer upper is the first index of right part + * + * Invariants: + * + * all in (low, lower] < pivot1 + * all in (k, upper) in [pivot1, pivot2] + * all in [upper, end) > pivot2 + */ + for (int unused = --lower, k = ++upper; --k > lower; ) { + short ak = a[k]; + + if (ak < pivot1) { // Move a[k] to the left side + while (a[++lower] < pivot1) { + if (lower == k) { + break; + } + } + if (a[lower] > pivot2) { + a[k] = a[--upper]; + a[upper] = a[lower]; + } else { + a[k] = a[lower]; + } + a[lower] = ak; + } else if (ak > pivot2) { // Move a[k] to the right side + a[k] = a[--upper]; + a[upper] = ak; + } + } + + /* + * Swap the pivots into their final positions. + */ + a[low] = a[lower]; a[lower] = pivot1; + a[end] = a[upper]; a[upper] = pivot2; + + /* + * Sort non-left parts recursively, + * excluding known pivots. + */ + sort(a, bits | 1, lower + 1, upper); + sort(a, bits | 1, upper + 1, high); + + } else { // Partitioning with one pivot + + /* + * Use the third of the five sorted elements as the pivot. + * This value is inexpensive approximation of the median. + */ + short pivot = a[e3]; + + /* + * The first element to be sorted is moved to the + * location formerly occupied by the pivot. After + * completion of partitioning the pivot is swapped + * back into its final position, and excluded from + * the next subsequent sorting. + */ + a[e3] = a[lower]; + + /* + * Dutch National Flag partitioning + * + * left part central part right part + * +------------------------------------------------------+ + * | < pivot | ? | == pivot | > pivot | + * +------------------------------------------------------+ + * ^ ^ ^ + * | | | + * lower k upper + * + * Pointer k is the last index of ?-part + * Pointer lower is the last index of left part + * Pointer upper is the first index of right part + * + * Invariants: + * + * all in (low, lower] < pivot + * all in (k, upper) == pivot + * all in [upper, end] > pivot + */ + for (int k = ++upper; --k > lower; ) { + short ak = a[k]; + + if (ak != pivot) { + a[k] = pivot; + + if (ak < pivot) { // Move a[k] to the left side + while (a[++lower] < pivot); + + if (a[lower] > pivot) { + a[--upper] = a[lower]; + } + a[lower] = ak; + } else { // ak > pivot - Move a[k] to the right side + a[--upper] = ak; + } + } + } + + /* + * Swap the pivot into its final position. + */ + a[low] = a[lower]; a[lower] = pivot; + + /* + * Sort the right part, excluding known pivot. + * All elements from the central part are + * equal and therefore already sorted. + */ + sort(a, bits | 1, upper, high); + } + high = lower; // Iterate along the left part + } + } + + /** + * Sorts the specified range of the array using insertion sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void insertionSort(short[] a, int low, int high) { + for (int i, k = low; ++k < high; ) { + short ai = a[i = k]; + + if (ai < a[i - 1]) { + do { + a[i] = a[--i]; + } while (i > low && ai < a[i - 1]); + + a[i ] = ai; + } + } + } + +// #[float] + + /** + * Sorts the specified range of the array using parallel merge + * sort and/or Dual-Pivot Quicksort. + * + * To balance the faster splitting and parallelism of merge sort + * with the faster element partitioning of Quicksort, ranges are + * subdivided in tiers such that, if there is enough parallelism, + * the four-way parallel merge is started, still ensuring enough + * parallelism to process the partitions. + * + * @param a the array to be sorted + * @param parallelism the parallelism level + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void sort(float[] a, int parallelism, int low, int high) { + /* + * Phase 1. Count the number of negative zero -0.0f, + * turn them into positive zero, and move all NaNs + * to the end of the array. + */ + int numNegativeZero = 0; + + for (int k = high; k > low; ) { + float ak = a[--k]; + + if (ak == 0.0f && Float.floatToRawIntBits(ak) < 0) { // ak is -0.0f + numNegativeZero += 1; + a[k] = 0.0f; + } else if (ak != ak) { // ak is NaN + a[k] = a[--high]; + a[high] = ak; + } + } + + /* + * Phase 2. Sort everything except NaNs, + * which are already in place. + */ + if (parallelism > 1 && high - low > MIN_PARALLEL_SORT_SIZE) { + new Sorter<>(a, parallelism, low, high - low, 0).invoke(); + } else { + sort(null, a, 0, low, high); + } + + /* + * Phase 3. Turn positive zero 0.0f + * back into negative zero -0.0f. + */ + if (++numNegativeZero == 1) { + return; + } + + /* + * Find the position one less than + * the index of the first zero. + */ + while (low <= high) { + int middle = (low + high) >>> 1; + + if (a[middle] < 0) { + low = middle + 1; + } else { + high = middle - 1; + } + } + + /* + * Replace the required number of 0.0f by -0.0f. + */ + while (--numNegativeZero > 0) { + a[++high] = -0.0f; + } + } + + /** + * Sorts the specified range of the array using Dual-Pivot Quicksort. + * + * @param sorter parallel context + * @param a the array to be sorted + * @param bits the combination of recursion depth and bit flag, where + * the right bit "0" indicates that range is the leftmost part + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void sort(Sorter sorter, float[] a, int bits, int low, int high) { + while (true) { + int size = high - low; + + /* + * Run adaptive mixed insertion sort on small non-leftmost parts. + */ + if (size < MAX_MIXED_INSERTION_SORT_SIZE + bits && (bits & 1) > 0) { + mixedInsertionSort(a, low, high); + return; + } + + /* + * Invoke insertion sort on small leftmost part. + */ + if (size < MAX_INSERTION_SORT_SIZE) { + insertionSort(a, low, high); + return; + } + + /* + * Try merging sort on large part. + */ + if (size > MIN_MERGING_SORT_SIZE * bits + && tryMergingSort(sorter, a, low, high)) { + return; + } + + /* + * Use an inexpensive approximation of the golden ratio + * to select five sample elements and determine pivots. + */ + int step = (size >> 2) + (size >> 3) + (size >> 8) + 1; + + /* + * Five elements around (and including) the central element + * will be used for pivot selection as described below. The + * unequal choice of spacing these elements was empirically + * determined to work well on a wide variety of inputs. + */ + int end = high - 1; + int e1 = low + step; + int e5 = end - step; + int e3 = (e1 + e5) >>> 1; + int e2 = (e1 + e3) >>> 1; + int e4 = (e3 + e5) >>> 1; + float a3 = a[e3]; + + boolean isRandom = + a[e1] > a[e2] || a[e2] > a3 || a3 > a[e4] || a[e4] > a[e5]; + + /* + * Sort these elements in place by the combination + * of 4-element sorting network and insertion sort. + * + * 1 ------------o-----o------------ + * | | + * 2 ------o-----|-----o-----o------ + * | | | + * 4 ------|-----o-----o-----o------ + * | | + * 5 ------o-----------o------------ + */ + if (a[e2] > a[e5]) { float t = a[e2]; a[e2] = a[e5]; a[e5] = t; } + if (a[e1] > a[e4]) { float t = a[e1]; a[e1] = a[e4]; a[e4] = t; } + 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[e2] > a[e4]) { float t = a[e2]; a[e2] = a[e4]; a[e4] = t; } + + /* + * Insert the third element. + */ + if (a3 < a[e2]) { + if (a3 < a[e1]) { + a[e3] = a[e2]; a[e2] = a[e1]; a[e1] = a3; + } else { + a[e3] = a[e2]; a[e2] = a3; + } + } else if (a3 > a[e4]) { + if (a3 > a[e5]) { + a[e3] = a[e4]; a[e4] = a[e5]; a[e5] = a3; + } else { + a[e3] = a[e4]; a[e4] = a3; + } + } + + /* + * Try Radix sort on large fully random data, + * taking into account parallel context. + */ + isRandom &= a[e1] < a[e2] && a[e2] < a[e3] && a[e3] < a[e4] && a[e4] < a[e5]; + + if (size > MIN_RADIX_SORT_SIZE && isRandom && (sorter == null || bits > 0) + && tryRadixSort(sorter, a, low, high)) { + return; + } + + /* + * Switch to heap sort, if execution time is quadratic. + */ + if ((bits += 2) > MAX_RECURSION_DEPTH) { + heapSort(a, low, high); + return; + } + + // Pointers + int lower = low; // The index of the last element of the left part + int upper = end; // The index of the first element of the right part + + /* + * Partitioning with two pivots on array of fully random elements. + */ + if (a[e1] < a[e2] && a[e2] < a[e3] && a[e3] < a[e4] && a[e4] < a[e5]) { + + /* + * Use the first and fifth of the five sorted elements as + * the pivots. These values are inexpensive approximation + * of tertiles. Note, that pivot1 < pivot2. + */ + float pivot1 = a[e1]; + float pivot2 = a[e5]; + + /* + * The first and the last elements to be sorted are moved + * to the locations formerly occupied by the pivots. When + * partitioning is completed, the pivots are swapped back + * into their final positions, and excluded from the next + * subsequent sorting. + */ + a[e1] = a[lower]; + a[e5] = a[upper]; + + /* + * Skip elements, which are less or greater than the pivots. + */ + while (a[++lower] < pivot1); + while (a[--upper] > pivot2); + + /* + * Backward 3-interval partitioning + * + * left part central part right part + * +------------------------------------------------------------------+ + * | < pivot1 | ? | pivot1 <= && <= pivot2 | > pivot2 | + * +------------------------------------------------------------------+ + * ^ ^ ^ + * | | | + * lower k upper + * + * Pointer k is the last index of ?-part + * Pointer lower is the last index of left part + * Pointer upper is the first index of right part + * + * Invariants: + * + * all in (low, lower] < pivot1 + * all in (k, upper) in [pivot1, pivot2] + * all in [upper, end) > pivot2 + */ + for (int unused = --lower, k = ++upper; --k > lower; ) { + float ak = a[k]; + + if (ak < pivot1) { // Move a[k] to the left side + while (a[++lower] < pivot1) { + if (lower == k) { + break; + } + } + if (a[lower] > pivot2) { + a[k] = a[--upper]; + a[upper] = a[lower]; + } else { + a[k] = a[lower]; + } + a[lower] = ak; + } else if (ak > pivot2) { // Move a[k] to the right side + a[k] = a[--upper]; + a[upper] = ak; + } + } + + /* + * Swap the pivots into their final positions. + */ + a[low] = a[lower]; a[lower] = pivot1; + a[end] = a[upper]; a[upper] = pivot2; + + /* + * Sort non-left parts recursively (possibly in parallel), + * excluding known pivots. + */ + if (size > MIN_PARALLEL_SORT_SIZE && sorter != null) { + sorter.fork(bits | 1, lower + 1, upper); + sorter.fork(bits | 1, upper + 1, high); + } else { + sort(sorter, a, bits | 1, lower + 1, upper); + sort(sorter, a, bits | 1, upper + 1, high); + } + + } else { // Partitioning with one pivot + + /* + * Use the third of the five sorted elements as the pivot. + * This value is inexpensive approximation of the median. + */ + float pivot = a[e3]; + + /* + * The first element to be sorted is moved to the + * location formerly occupied by the pivot. After + * completion of partitioning the pivot is swapped + * back into its final position, and excluded from + * the next subsequent sorting. + */ + a[e3] = a[lower]; + + /* + * Dutch National Flag partitioning + * + * left part central part right part + * +------------------------------------------------------+ + * | < pivot | ? | == pivot | > pivot | + * +------------------------------------------------------+ + * ^ ^ ^ + * | | | + * lower k upper + * + * Pointer k is the last index of ?-part + * Pointer lower is the last index of left part + * Pointer upper is the first index of right part + * + * Invariants: + * + * all in (low, lower] < pivot + * all in (k, upper) == pivot + * all in [upper, end] > pivot + */ + for (int k = ++upper; --k > lower; ) { + float ak = a[k]; + + if (ak != pivot) { + a[k] = pivot; + + if (ak < pivot) { // Move a[k] to the left side + while (a[++lower] < pivot); + + if (a[lower] > pivot) { + a[--upper] = a[lower]; + } + a[lower] = ak; + } else { // ak > pivot - Move a[k] to the right side + a[--upper] = ak; + } + } + } + + /* + * Swap the pivot into its final position. + */ + a[low] = a[lower]; a[lower] = pivot; + + /* + * Sort the right part (possibly in parallel), excluding + * known pivot. All elements from the central part are + * equal and therefore already sorted. + */ + if (size > MIN_PARALLEL_SORT_SIZE && sorter != null) { + sorter.fork(bits | 1, upper, high); + } else { + sort(sorter, a, bits | 1, upper, high); + } + } + high = lower; // Iterate along the left part + } + } + + /** + * Sorts the specified range of the array using mixed insertion sort. + * + * Mixed insertion sort is combination of pin insertion sort, + * simple insertion sort and pair insertion sort. + * + * In the context of Dual-Pivot Quicksort, the pivot element + * from the left part plays the role of sentinel, because it + * is less than any elements from the given part. Therefore, + * expensive check of the left range can be skipped on each + * iteration unless it is the leftmost call. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void mixedInsertionSort(float[] a, int low, int high) { + + /* + * Split part for pin and pair insertion sorts. + */ + int end = high - 3 * ((high - low) >> 3 << 1); + + /* + * Invoke simple insertion sort on small part. + */ + if (end == high) { + for (int i; ++low < high; ) { + float ai = a[i = low]; + + while (ai < a[i - 1]) { + a[i] = a[--i]; + } + a[i] = ai; + } + return; + } + + /* + * Start with pin insertion sort. + */ + for (int i, p = high; ++low < end; ) { + float ai = a[i = low], pin = a[--p]; + + /* + * Swap larger element with pin. + */ + if (ai > pin) { + ai = pin; + a[p] = a[i]; + } + + /* + * Insert element into sorted part. + */ + while (ai < a[i - 1]) { + a[i] = a[--i]; + } + a[i] = ai; + } + + /* + * Finish with pair insertion sort. + */ + for (int i; low < high; ++low) { + float a1 = a[i = low], a2 = a[++low]; + + /* + * Insert two elements per iteration: at first, insert the + * larger element and then insert the smaller element, but + * from the position where the larger element was inserted. + */ + if (a1 > a2) { + + while (a1 < a[--i]) { + a[i + 2] = a[i]; + } + a[++i + 1] = a1; + + while (a2 < a[--i]) { + a[i + 1] = a[i]; + } + a[i + 1] = a2; + + } else if (a1 < a[i - 1]) { + + while (a2 < a[--i]) { + a[i + 2] = a[i]; + } + a[++i + 1] = a2; + + while (a1 < a[--i]) { + a[i + 1] = a[i]; + } + a[i + 1] = a1; + } + } + } + + /** + * Sorts the specified range of the array using insertion sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void insertionSort(float[] a, int low, int high) { + for (int i, k = low; ++k < high; ) { + float ai = a[i = k]; + + if (ai < a[i - 1]) { + do { + a[i] = a[--i]; + } while (i > low && ai < a[i - 1]); + + a[i ] = ai; + } + } + } + + /** + * Tries to sort the specified range of the array using merging sort. + * + * @param sorter parallel context + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + * @return {@code true} if the array is finally sorted, otherwise {@code false} + */ + static boolean tryMergingSort(Sorter sorter, float[] a, int low, int high) { + + /* + * The element run[i] holds the start index + * of i-th sequence in non-descending order. + */ + int count = 1; + int[] run = null; + + /* + * Identify all possible runs. + */ + for (int k = low + 1, last = low; k < high; ) { + + /* + * Find the next run. + */ + if (a[k - 1] < a[k]) { + + // Identify ascending sequence + while (++k < high && a[k - 1] <= a[k]); + + } else if (a[k - 1] > a[k]) { + + // Identify descending sequence + while (++k < high && a[k - 1] >= a[k]); + + // Reverse into ascending order + for (int i = last - 1, j = k; ++i < --j && a[i] > a[j]; ) { + float ai = a[i]; a[i] = a[j]; a[j] = ai; + } + } else { // Identify constant sequence + for (float ak = a[k]; ++k < high && ak == a[k]; ); + + if (k < high) { + continue; + } + } + + /* + * Check if the runs are too + * long to continue scanning. + */ + if (count > 6 && k - low < count * MIN_RUN_SIZE) { + return false; + } + + /* + * Process the run. + */ + if (run == null) { + + if (k == high) { + /* + * Array is monotonous sequence + * and therefore already sorted. + */ + return true; + } + + run = new int[((high - low) >> 9) & 0x1FF | 0x3F]; + run[0] = low; + + } else if (a[last - 1] > a[last]) { // Start the new run + + if (++count == run.length) { + /* + * Array is not highly structured. + */ + return false; + } + } + + /* + * Save the current run. + */ + run[count] = (last = k); + + /* + * Check single-element run at the end. + */ + if (++k == high) { + --k; + } + } + + /* + * Merge all runs. + */ + if (count > 1) { + float[] b; int offset = low; + + if (sorter != null && (b = sorter.b) != null) { + offset = sorter.offset; + } else if ((b = tryAllocate(float[].class, high - low)) == null) { + return false; + } + mergeRuns(a, b, offset, 1, sorter != null, run, 0, count); + } + return true; + } + + /** + * Merges the specified runs. + * + * @param a the source array + * @param b the temporary buffer used in merging + * @param offset the start index in the source, inclusive + * @param aim specifies merging: to source ( > 0), buffer ( < 0) or any ( == 0) + * @param parallel indicates whether merging is performed in parallel + * @param run the start indexes of the runs, inclusive + * @param lo the start index of the first run, inclusive + * @param hi the start index of the last run, inclusive + * @return the destination where runs are merged + */ + private static float[] mergeRuns(float[] a, float[] b, int offset, + int aim, boolean parallel, int[] run, int lo, int hi) { + + if (hi - lo == 1) { + if (aim >= 0) { + return a; + } + System.arraycopy(a, run[lo], b, run[lo] - offset, run[hi] - run[lo]); + return b; + } + + /* + * Split into approximately equal parts. + */ + int mi = lo, rmi = (run[lo] + run[hi]) >>> 1; + while (run[++mi + 1] <= rmi); + + /* + * Merge runs of each part. + */ + float[] a1 = mergeRuns(a, b, offset, -aim, parallel, run, lo, mi); + float[] a2 = mergeRuns(a, b, offset, 0, parallel, run, mi, hi); + float[] dst = a1 == a ? b : a; + + int k = a1 == a ? run[lo] - offset : run[lo]; + int lo1 = a1 == b ? run[lo] - offset : run[lo]; + int hi1 = a1 == b ? run[mi] - offset : run[mi]; + int lo2 = a2 == b ? run[mi] - offset : run[mi]; + int hi2 = a2 == b ? run[hi] - offset : run[hi]; + + /* + * Merge the left and right parts. + */ + if (hi1 - lo1 > MIN_PARALLEL_SORT_SIZE && parallel) { + new Merger<>(null, dst, k, a1, lo1, hi1, a2, lo2, hi2).invoke(); + } else { + mergeParts(null, dst, k, a1, lo1, hi1, a2, lo2, hi2); + } + return dst; + } + + /** + * Merges the sorted parts. + * + * @param merger parallel context + * @param dst the destination where parts are merged + * @param k the start index of the destination, inclusive + * @param a1 the first part + * @param lo1 the start index of the first part, inclusive + * @param hi1 the end index of the first part, exclusive + * @param a2 the second part + * @param lo2 the start index of the second part, inclusive + * @param hi2 the end index of the second part, exclusive + */ + private static void mergeParts(Merger merger, float[] dst, int k, + float[] a1, int lo1, int hi1, float[] a2, int lo2, int hi2) { + + if (merger != null && a1 == a2) { + + while (true) { + + /* + * The first part must be larger. + */ + if (hi1 - lo1 < hi2 - lo2) { + int lo = lo1; lo1 = lo2; lo2 = lo; + int hi = hi1; hi1 = hi2; hi2 = hi; + } + + /* + * Small parts will be merged sequentially. + */ + if (hi1 - lo1 < MIN_PARALLEL_SORT_SIZE) { + break; + } + + /* + * Find the median of the larger part. + */ + int mi1 = (lo1 + hi1) >>> 1; + float key = a1[mi1]; + int mi2 = hi2; + + /* + * Divide the smaller part. + */ + for (int loo = lo2; loo < mi2; ) { + int t = (loo + mi2) >>> 1; + + if (key > a2[t]) { + loo = t + 1; + } else { + mi2 = t; + } + } + + /* + * Reserve space for the left part. + */ + int d = mi2 - lo2 + mi1 - lo1; + + /* + * Merge the right part in parallel. + */ + merger.fork(k + d, mi1, hi1, mi2, hi2); + + /* + * Iterate along the left part. + */ + hi1 = mi1; + hi2 = mi2; + } + } + + /* + * Merge small parts sequentially. + */ + while (lo1 < hi1 && lo2 < hi2) { + dst[k++] = a1[lo1] < a2[lo2] ? a1[lo1++] : a2[lo2++]; + } + if (dst != a1 || k < lo1) { + while (lo1 < hi1) { + dst[k++] = a1[lo1++]; + } + } + if (dst != a2 || k < lo2) { + while (lo2 < hi2) { + dst[k++] = a2[lo2++]; + } + } + } + + /** + * Tries to sort the specified range of the array + * using LSD (The Least Significant Digit) Radix sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + * @return {@code true} if the array is finally sorted, otherwise {@code false} + */ + static boolean tryRadixSort(Sorter sorter, float[] a, int low, int high) { + float[] b; int offset = low, size = high - low; + + /* + * Allocate additional buffer. + */ + if (sorter != null && (b = sorter.b) != null) { + offset = sorter.offset; + } else if ((b = tryAllocate(float[].class, size)) == null) { + return false; + } + + int start = low - offset; + int last = high - offset; + + /* + * Count the number of all digits. + */ + int[] count1 = new int[1024]; + int[] count2 = new int[2048]; + int[] count3 = new int[2048]; + + for (int i = low; i < high; ++i) { + ++count1[ fti(a[i]) & 0x3FF]; + ++count2[(fti(a[i]) >>> 10) & 0x7FF]; + ++count3[(fti(a[i]) >>> 21) & 0x7FF]; + } + + /* + * Detect digits to be processed. + */ + boolean processDigit1 = processDigit(count1, size, low); + boolean processDigit2 = processDigit(count2, size, low); + boolean processDigit3 = processDigit(count3, size, low); + + /* + * Process the 1-st digit. + */ + if (processDigit1) { + for (int i = high; i > low; ) { + b[--count1[fti(a[--i]) & 0x3FF] - offset] = a[i]; + } + } + + /* + * Process the 2-nd digit. + */ + if (processDigit2) { + if (processDigit1) { + for (int i = last; i > start; ) { + a[--count2[(fti(b[--i]) >>> 10) & 0x7FF]] = b[i]; + } + } else { + for (int i = high; i > low; ) { + b[--count2[(fti(a[--i]) >>> 10) & 0x7FF] - offset] = a[i]; + } + } + } + + /* + * Process the 3-rd digit. + */ + if (processDigit3) { + if (processDigit1 ^ processDigit2) { + for (int i = last; i > start; ) { + a[--count3[(fti(b[--i]) >>> 21) & 0x7FF]] = b[i]; + } + } else { + for (int i = high; i > low; ) { + b[--count3[(fti(a[--i]) >>> 21) & 0x7FF] - offset] = a[i]; + } + } + } + + /* + * Copy the buffer to original array, if we process ood number of digits. + */ + if (processDigit1 ^ processDigit2 ^ processDigit3) { + System.arraycopy(b, low - offset, a, low, size); + } + return true; + } + + /** + * Returns masked bits that represent the float value. + * + * @param f the given value + * @return masked bits + */ + private static int fti(float f) { + int x = Float.floatToRawIntBits(f); + return x ^ ((x >> 31) | 0x80000000); + } + + /** + * Sorts the specified range of the array using heap sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void heapSort(float[] a, int low, int high) { + for (int k = (low + high) >>> 1; k > low; ) { + pushDown(a, --k, a[k], low, high); + } + while (--high > low) { + float max = a[low]; + pushDown(a, low, a[high], low, high); + a[high] = max; + } + } + + /** + * Pushes specified element down during heap sort. + * + * @param a the given array + * @param p the start index + * @param value the given element + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + private static void pushDown(float[] a, int p, float value, int low, int high) { + for (int k ;; a[p] = a[p = k]) { + k = (p << 1) - low + 2; // Index of the right child + + if (k > high) { + break; + } + if (k == high || a[k] < a[k - 1]) { + --k; + } + if (a[k] <= value) { + break; + } + } + a[p] = value; + } + +// #[double] + + /** + * Sorts the specified range of the array using parallel merge + * sort and/or Dual-Pivot Quicksort. + * + * To balance the faster splitting and parallelism of merge sort + * with the faster element partitioning of Quicksort, ranges are + * subdivided in tiers such that, if there is enough parallelism, + * the four-way parallel merge is started, still ensuring enough + * parallelism to process the partitions. + * + * @param a the array to be sorted + * @param parallelism the parallelism level + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void sort(double[] a, int parallelism, int low, int high) { + /* + * Phase 1. Count the number of negative zero -0.0d, + * turn them into positive zero, and move all NaNs + * to the end of the array. + */ + int numNegativeZero = 0; + + for (int k = high; k > low; ) { + double ak = a[--k]; + + if (ak == 0.0d && Double.doubleToRawLongBits(ak) < 0) { // ak is -0.0d + numNegativeZero += 1; + a[k] = 0.0d; + } else if (ak != ak) { // ak is NaN + a[k] = a[--high]; + a[high] = ak; + } + } + + /* + * Phase 2. Sort everything except NaNs, + * which are already in place. + */ + if (parallelism > 1 && high - low > MIN_PARALLEL_SORT_SIZE) { + new Sorter<>(a, parallelism, low, high - low, 0).invoke(); + } else { + sort(null, a, 0, low, high); + } + + /* + * Phase 3. Turn positive zero 0.0d + * back into negative zero -0.0d. + */ + if (++numNegativeZero == 1) { + return; + } + + /* + * Find the position one less than + * the index of the first zero. + */ + while (low <= high) { + int middle = (low + high) >>> 1; + + if (a[middle] < 0) { + low = middle + 1; + } else { + high = middle - 1; + } + } + + /* + * Replace the required number of 0.0d by -0.0d. + */ + while (--numNegativeZero > 0) { + a[++high] = -0.0d; + } + } + + /** + * Sorts the specified range of the array using Dual-Pivot Quicksort. + * + * @param sorter parallel context + * @param a the array to be sorted + * @param bits the combination of recursion depth and bit flag, where + * the right bit "0" indicates that range is the leftmost part + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void sort(Sorter sorter, double[] a, int bits, int low, int high) { + while (true) { + int size = high - low; + + /* + * Run adaptive mixed insertion sort on small non-leftmost parts. + */ + if (size < MAX_MIXED_INSERTION_SORT_SIZE + bits && (bits & 1) > 0) { + mixedInsertionSort(a, low, high); + return; + } + + /* + * Invoke insertion sort on small leftmost part. + */ + if (size < MAX_INSERTION_SORT_SIZE) { + insertionSort(a, low, high); + return; + } + + /* + * Try merging sort on large part. + */ + if (size > MIN_MERGING_SORT_SIZE * bits + && tryMergingSort(sorter, a, low, high)) { + return; + } + + /* + * Use an inexpensive approximation of the golden ratio + * to select five sample elements and determine pivots. + */ + int step = (size >> 2) + (size >> 3) + (size >> 8) + 1; + + /* + * Five elements around (and including) the central element + * will be used for pivot selection as described below. The + * unequal choice of spacing these elements was empirically + * determined to work well on a wide variety of inputs. + */ + int end = high - 1; + int e1 = low + step; + int e5 = end - step; + int e3 = (e1 + e5) >>> 1; + int e2 = (e1 + e3) >>> 1; + int e4 = (e3 + e5) >>> 1; + double a3 = a[e3]; + + boolean isRandom = + a[e1] > a[e2] || a[e2] > a3 || a3 > a[e4] || a[e4] > a[e5]; + + /* + * Sort these elements in place by the combination + * of 4-element sorting network and insertion sort. + * + * 1 ------------o-----o------------ + * | | + * 2 ------o-----|-----o-----o------ + * | | | + * 4 ------|-----o-----o-----o------ + * | | + * 5 ------o-----------o------------ + */ + if (a[e2] > a[e5]) { double t = a[e2]; a[e2] = a[e5]; a[e5] = t; } + if (a[e1] > a[e4]) { double t = a[e1]; a[e1] = a[e4]; a[e4] = t; } + 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[e2] > a[e4]) { double t = a[e2]; a[e2] = a[e4]; a[e4] = t; } + + /* + * Insert the third element. + */ + if (a3 < a[e2]) { + if (a3 < a[e1]) { + a[e3] = a[e2]; a[e2] = a[e1]; a[e1] = a3; + } else { + a[e3] = a[e2]; a[e2] = a3; + } + } else if (a3 > a[e4]) { + if (a3 > a[e5]) { + a[e3] = a[e4]; a[e4] = a[e5]; a[e5] = a3; + } else { + a[e3] = a[e4]; a[e4] = a3; + } + } + + /* + * Try Radix sort on large fully random data, + * taking into account parallel context. + */ + isRandom &= a[e1] < a[e2] && a[e2] < a[e3] && a[e3] < a[e4] && a[e4] < a[e5]; + + if (size > MIN_RADIX_SORT_SIZE && isRandom && (sorter == null || bits > 0) + && tryRadixSort(sorter, a, low, high)) { + return; + } + + /* + * Switch to heap sort, if execution time is quadratic. + */ + if ((bits += 2) > MAX_RECURSION_DEPTH) { + heapSort(a, low, high); + return; + } + + // Pointers + int lower = low; // The index of the last element of the left part + int upper = end; // The index of the first element of the right part + + /* + * Partitioning with two pivots on array of fully random elements. + */ + if (a[e1] < a[e2] && a[e2] < a[e3] && a[e3] < a[e4] && a[e4] < a[e5]) { + + /* + * Use the first and fifth of the five sorted elements as + * the pivots. These values are inexpensive approximation + * of tertiles. Note, that pivot1 < pivot2. + */ + double pivot1 = a[e1]; + double pivot2 = a[e5]; + + /* + * The first and the last elements to be sorted are moved + * to the locations formerly occupied by the pivots. When + * partitioning is completed, the pivots are swapped back + * into their final positions, and excluded from the next + * subsequent sorting. + */ + a[e1] = a[lower]; + a[e5] = a[upper]; + + /* + * Skip elements, which are less or greater than the pivots. + */ + while (a[++lower] < pivot1); + while (a[--upper] > pivot2); + + /* + * Backward 3-interval partitioning + * + * left part central part right part + * +------------------------------------------------------------------+ + * | < pivot1 | ? | pivot1 <= && <= pivot2 | > pivot2 | + * +------------------------------------------------------------------+ + * ^ ^ ^ + * | | | + * lower k upper + * + * Pointer k is the last index of ?-part + * Pointer lower is the last index of left part + * Pointer upper is the first index of right part + * + * Invariants: + * + * all in (low, lower] < pivot1 + * all in (k, upper) in [pivot1, pivot2] + * all in [upper, end) > pivot2 + */ + for (int unused = --lower, k = ++upper; --k > lower; ) { + double ak = a[k]; + + if (ak < pivot1) { // Move a[k] to the left side + while (a[++lower] < pivot1) { + if (lower == k) { + break; + } + } + if (a[lower] > pivot2) { + a[k] = a[--upper]; + a[upper] = a[lower]; + } else { + a[k] = a[lower]; + } + a[lower] = ak; + } else if (ak > pivot2) { // Move a[k] to the right side + a[k] = a[--upper]; + a[upper] = ak; + } + } + + /* + * Swap the pivots into their final positions. + */ + a[low] = a[lower]; a[lower] = pivot1; + a[end] = a[upper]; a[upper] = pivot2; + + /* + * Sort non-left parts recursively (possibly in parallel), + * excluding known pivots. + */ + if (size > MIN_PARALLEL_SORT_SIZE && sorter != null) { + sorter.fork(bits | 1, lower + 1, upper); + sorter.fork(bits | 1, upper + 1, high); + } else { + sort(sorter, a, bits | 1, lower + 1, upper); + sort(sorter, a, bits | 1, upper + 1, high); + } + + } else { // Partitioning with one pivot + + /* + * Use the third of the five sorted elements as the pivot. + * This value is inexpensive approximation of the median. + */ + double pivot = a[e3]; + + /* + * The first element to be sorted is moved to the + * location formerly occupied by the pivot. After + * completion of partitioning the pivot is swapped + * back into its final position, and excluded from + * the next subsequent sorting. + */ + a[e3] = a[lower]; + + /* + * Dutch National Flag partitioning + * + * left part central part right part + * +------------------------------------------------------+ + * | < pivot | ? | == pivot | > pivot | + * +------------------------------------------------------+ + * ^ ^ ^ + * | | | + * lower k upper + * + * Pointer k is the last index of ?-part + * Pointer lower is the last index of left part + * Pointer upper is the first index of right part + * + * Invariants: + * + * all in (low, lower] < pivot + * all in (k, upper) == pivot + * all in [upper, end] > pivot + */ + for (int k = ++upper; --k > lower; ) { + double ak = a[k]; + + if (ak != pivot) { + a[k] = pivot; + + if (ak < pivot) { // Move a[k] to the left side + while (a[++lower] < pivot); + + if (a[lower] > pivot) { + a[--upper] = a[lower]; + } + a[lower] = ak; + } else { // ak > pivot - Move a[k] to the right side + a[--upper] = ak; + } + } + } + + /* + * Swap the pivot into its final position. + */ + a[low] = a[lower]; a[lower] = pivot; + + /* + * Sort the right part (possibly in parallel), excluding + * known pivot. All elements from the central part are + * equal and therefore already sorted. + */ + if (size > MIN_PARALLEL_SORT_SIZE && sorter != null) { + sorter.fork(bits | 1, upper, high); + } else { + sort(sorter, a, bits | 1, upper, high); + } + } + high = lower; // Iterate along the left part + } + } + + /** + * Sorts the specified range of the array using mixed insertion sort. + * + * Mixed insertion sort is combination of pin insertion sort, + * simple insertion sort and pair insertion sort. + * + * In the context of Dual-Pivot Quicksort, the pivot element + * from the left part plays the role of sentinel, because it + * is less than any elements from the given part. Therefore, + * expensive check of the left range can be skipped on each + * iteration unless it is the leftmost call. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void mixedInsertionSort(double[] a, int low, int high) { + + /* + * Split part for pin and pair insertion sorts. + */ + int end = high - 3 * ((high - low) >> 3 << 1); + + /* + * Invoke simple insertion sort on small part. + */ + if (end == high) { + for (int i; ++low < high; ) { + double ai = a[i = low]; + + while (ai < a[i - 1]) { + a[i] = a[--i]; + } + a[i] = ai; + } + return; + } + + /* + * Start with pin insertion sort. + */ + for (int i, p = high; ++low < end; ) { + double ai = a[i = low], pin = a[--p]; + + /* + * Swap larger element with pin. + */ + if (ai > pin) { + ai = pin; + a[p] = a[i]; + } + + /* + * Insert element into sorted part. + */ + while (ai < a[i - 1]) { + a[i] = a[--i]; + } + a[i] = ai; + } + + /* + * Finish with pair insertion sort. + */ + for (int i; low < high; ++low) { + double a1 = a[i = low], a2 = a[++low]; + + /* + * Insert two elements per iteration: at first, insert the + * larger element and then insert the smaller element, but + * from the position where the larger element was inserted. + */ + if (a1 > a2) { + + while (a1 < a[--i]) { + a[i + 2] = a[i]; + } + a[++i + 1] = a1; + + while (a2 < a[--i]) { + a[i + 1] = a[i]; + } + a[i + 1] = a2; + + } else if (a1 < a[i - 1]) { + + while (a2 < a[--i]) { + a[i + 2] = a[i]; + } + a[++i + 1] = a2; + + while (a1 < a[--i]) { + a[i + 1] = a[i]; + } + a[i + 1] = a1; + } + } + } + + /** + * Sorts the specified range of the array using insertion sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void insertionSort(double[] a, int low, int high) { + for (int i, k = low; ++k < high; ) { + double ai = a[i = k]; + + if (ai < a[i - 1]) { + do { + a[i] = a[--i]; + } while (i > low && ai < a[i - 1]); + + a[i ] = ai; + } + } + } + + /** + * Tries to sort the specified range of the array using merging sort. + * + * @param sorter parallel context + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + * @return {@code true} if the array is finally sorted, otherwise {@code false} + */ + static boolean tryMergingSort(Sorter sorter, double[] a, int low, int high) { + + /* + * The element run[i] holds the start index + * of i-th sequence in non-descending order. + */ + int count = 1; + int[] run = null; + + /* + * Identify all possible runs. + */ + for (int k = low + 1, last = low; k < high; ) { + + /* + * Find the next run. + */ + if (a[k - 1] < a[k]) { + + // Identify ascending sequence + while (++k < high && a[k - 1] <= a[k]); + + } else if (a[k - 1] > a[k]) { + + // Identify descending sequence + while (++k < high && a[k - 1] >= a[k]); + + // Reverse into ascending order + for (int i = last - 1, j = k; ++i < --j && a[i] > a[j]; ) { + double ai = a[i]; a[i] = a[j]; a[j] = ai; + } + } else { // Identify constant sequence + for (double ak = a[k]; ++k < high && ak == a[k]; ); + + if (k < high) { + continue; + } + } + + /* + * Check if the runs are too + * long to continue scanning. + */ + if (count > 6 && k - low < count * MIN_RUN_SIZE) { + return false; + } + + /* + * Process the run. + */ + if (run == null) { + + if (k == high) { + /* + * Array is monotonous sequence + * and therefore already sorted. + */ + return true; + } + + run = new int[((high - low) >> 9) & 0x1FF | 0x3F]; + run[0] = low; + + } else if (a[last - 1] > a[last]) { // Start the new run + + if (++count == run.length) { + /* + * Array is not highly structured. + */ + return false; + } + } + + /* + * Save the current run. + */ + run[count] = (last = k); + + /* + * Check single-element run at the end. + */ + if (++k == high) { + --k; + } + } + + /* + * Merge all runs. + */ + if (count > 1) { + double[] b; int offset = low; + + if (sorter != null && (b = sorter.b) != null) { + offset = sorter.offset; + } else if ((b = tryAllocate(double[].class, high - low)) == null) { + return false; + } + mergeRuns(a, b, offset, 1, sorter != null, run, 0, count); + } + return true; + } + + /** + * Merges the specified runs. + * + * @param a the source array + * @param b the temporary buffer used in merging + * @param offset the start index in the source, inclusive + * @param aim specifies merging: to source ( > 0), buffer ( < 0) or any ( == 0) + * @param parallel indicates whether merging is performed in parallel + * @param run the start indexes of the runs, inclusive + * @param lo the start index of the first run, inclusive + * @param hi the start index of the last run, inclusive + * @return the destination where runs are merged + */ + private static double[] mergeRuns(double[] a, double[] b, int offset, + int aim, boolean parallel, int[] run, int lo, int hi) { + + if (hi - lo == 1) { + if (aim >= 0) { + return a; + } + System.arraycopy(a, run[lo], b, run[lo] - offset, run[hi] - run[lo]); + return b; + } + + /* + * Split into approximately equal parts. + */ + int mi = lo, rmi = (run[lo] + run[hi]) >>> 1; + while (run[++mi + 1] <= rmi); + + /* + * Merge runs of each part. + */ + double[] a1 = mergeRuns(a, b, offset, -aim, parallel, run, lo, mi); + double[] a2 = mergeRuns(a, b, offset, 0, parallel, run, mi, hi); + double[] dst = a1 == a ? b : a; + + int k = a1 == a ? run[lo] - offset : run[lo]; + int lo1 = a1 == b ? run[lo] - offset : run[lo]; + int hi1 = a1 == b ? run[mi] - offset : run[mi]; + int lo2 = a2 == b ? run[mi] - offset : run[mi]; + int hi2 = a2 == b ? run[hi] - offset : run[hi]; + + /* + * Merge the left and right parts. + */ + if (hi1 - lo1 > MIN_PARALLEL_SORT_SIZE && parallel) { + new Merger<>(null, dst, k, a1, lo1, hi1, a2, lo2, hi2).invoke(); + } else { + mergeParts(null, dst, k, a1, lo1, hi1, a2, lo2, hi2); + } + return dst; + } + + /** + * Merges the sorted parts. + * + * @param merger parallel context + * @param dst the destination where parts are merged + * @param k the start index of the destination, inclusive + * @param a1 the first part + * @param lo1 the start index of the first part, inclusive + * @param hi1 the end index of the first part, exclusive + * @param a2 the second part + * @param lo2 the start index of the second part, inclusive + * @param hi2 the end index of the second part, exclusive + */ + private static void mergeParts(Merger merger, double[] dst, int k, + double[] a1, int lo1, int hi1, double[] a2, int lo2, int hi2) { + + if (merger != null && a1 == a2) { + + while (true) { + + /* + * The first part must be larger. + */ + if (hi1 - lo1 < hi2 - lo2) { + int lo = lo1; lo1 = lo2; lo2 = lo; + int hi = hi1; hi1 = hi2; hi2 = hi; + } + + /* + * Small parts will be merged sequentially. + */ + if (hi1 - lo1 < MIN_PARALLEL_SORT_SIZE) { + break; + } + + /* + * Find the median of the larger part. + */ + int mi1 = (lo1 + hi1) >>> 1; + double key = a1[mi1]; + int mi2 = hi2; + + /* + * Divide the smaller part. + */ + for (int loo = lo2; loo < mi2; ) { + int t = (loo + mi2) >>> 1; + + if (key > a2[t]) { + loo = t + 1; + } else { + mi2 = t; + } + } + + /* + * Reserve space for the left part. + */ + int d = mi2 - lo2 + mi1 - lo1; + + /* + * Merge the right part in parallel. + */ + merger.fork(k + d, mi1, hi1, mi2, hi2); + + /* + * Iterate along the left part. + */ + hi1 = mi1; + hi2 = mi2; + } + } + + /* + * Merge small parts sequentially. + */ + while (lo1 < hi1 && lo2 < hi2) { + dst[k++] = a1[lo1] < a2[lo2] ? a1[lo1++] : a2[lo2++]; + } + if (dst != a1 || k < lo1) { + while (lo1 < hi1) { + dst[k++] = a1[lo1++]; + } + } + if (dst != a2 || k < lo2) { + while (lo2 < hi2) { + dst[k++] = a2[lo2++]; + } + } + } + + /** + * Tries to sort the specified range of the array + * using LSD (The Least Significant Digit) Radix sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + * @return {@code true} if the array is finally sorted, otherwise {@code false} + */ + static boolean tryRadixSort(Sorter sorter, double[] a, int low, int high) { + double[] b; int offset = low, size = high - low; + + /* + * Allocate additional buffer. + */ + if (sorter != null && (b = sorter.b) != null) { + offset = sorter.offset; + } else if ((b = tryAllocate(double[].class, size)) == null) { + return false; + } + + int start = low - offset; + int last = high - offset; + + /* + * Count the number of all digits. + */ + int[] count1 = new int[1024]; + int[] count2 = new int[2048]; + int[] count3 = new int[2048]; + int[] count4 = new int[2048]; + int[] count5 = new int[2048]; + int[] count6 = new int[1024]; + + for (int i = low; i < high; ++i) { + ++count1[(int) (dtl(a[i]) & 0x3FF)]; + ++count2[(int) ((dtl(a[i]) >>> 10) & 0x7FF)]; + ++count3[(int) ((dtl(a[i]) >>> 21) & 0x7FF)]; + ++count4[(int) ((dtl(a[i]) >>> 32) & 0x7FF)]; + ++count5[(int) ((dtl(a[i]) >>> 43) & 0x7FF)]; + ++count6[(int) ((dtl(a[i]) >>> 54) & 0x3FF)]; + } + + /* + * Detect digits to be processed. + */ + boolean processDigit1 = processDigit(count1, size, low); + boolean processDigit2 = processDigit(count2, size, low); + boolean processDigit3 = processDigit(count3, size, low); + boolean processDigit4 = processDigit(count4, size, low); + boolean processDigit5 = processDigit(count5, size, low); + boolean processDigit6 = processDigit(count6, size, low); + + /* + * Process the 1-st digit. + */ + if (processDigit1) { + for (int i = high; i > low; ) { + b[--count1[(int) (dtl(a[--i]) & 0x3FF)] - offset] = a[i]; + } + } + + /* + * Process the 2-nd digit. + */ + if (processDigit2) { + if (processDigit1) { + for (int i = last; i > start; ) { + a[--count2[(int) ((dtl(b[--i]) >>> 10) & 0x7FF)]] = b[i]; + } + } else { + for (int i = high; i > low; ) { + b[--count2[(int) ((dtl(a[--i]) >>> 10) & 0x7FF)] - offset] = a[i]; + } + } + } + + /* + * Process the 3-rd digit. + */ + if (processDigit3) { + if (processDigit1 ^ processDigit2) { + for (int i = last; i > start; ) { + a[--count3[(int) ((dtl(b[--i]) >>> 21) & 0x7FF)]] = b[i]; + } + } else { + for (int i = high; i > low; ) { + b[--count3[(int) ((dtl(a[--i]) >>> 21) & 0x7FF)] - offset] = a[i]; + } + } + } + + /* + * Process the 4-th digit. + */ + if (processDigit4) { + if (processDigit1 ^ processDigit2 ^ processDigit3) { + for (int i = last; i > start; ) { + a[--count4[(int) ((dtl(b[--i]) >>> 32) & 0x7FF)]] = b[i]; + } + } else { + for (int i = high; i > low; ) { + b[--count4[(int) ((dtl(a[--i]) >>> 32) & 0x7FF)] - offset] = a[i]; + } + } + } + + /* + * Process the 5-th digit. + */ + if (processDigit5) { + if (processDigit1 ^ processDigit2 ^ processDigit3 ^ processDigit4) { + for (int i = last; i > start; ) { + a[--count5[(int) ((dtl(b[--i]) >>> 43) & 0x7FF)]] = b[i]; + } + } else { + for (int i = high; i > low; ) { + b[--count5[(int) ((dtl(a[--i]) >>> 43) & 0x7FF)] - offset] = a[i]; + } + } + } + + /* + * Process the 6-th digit. + */ + if (processDigit6) { + if (processDigit1 ^ processDigit2 ^ processDigit3 ^ processDigit4 ^ processDigit5) { + for (int i = last; i > start; ) { + a[--count6[(int) ((dtl(b[--i]) >>> 54) & 0x3FF)]] = b[i]; + } + } else { + for (int i = high; i > low; ) { + b[--count6[(int) ((dtl(a[--i]) >>> 54) & 0x3FF)] - offset] = a[i]; + } + } + } + + /* + * Copy the buffer to original array, if we process ood number of digits. + */ + if (processDigit1 ^ processDigit2 ^ processDigit3 ^ processDigit4 ^ processDigit5 ^ processDigit6) { + System.arraycopy(b, low - offset, a, low, size); + } + return true; + } + + /** + * Returns masked bits that represent the double value. + * + * @param d the given value + * @return masked bits + */ + private static long dtl(double d) { + long x = Double.doubleToRawLongBits(d); + return x ^ ((x >> 63) | 0x8000000000000000L); + } + + /** + * Sorts the specified range of the array using heap sort. + * + * @param a the array to be sorted + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + static void heapSort(double[] a, int low, int high) { + for (int k = (low + high) >>> 1; k > low; ) { + pushDown(a, --k, a[k], low, high); + } + while (--high > low) { + double max = a[low]; + pushDown(a, low, a[high], low, high); + a[high] = max; + } + } + + /** + * Pushes specified element down during heap sort. + * + * @param a the given array + * @param p the start index + * @param value the given element + * @param low the index of the first element, inclusive, to be sorted + * @param high the index of the last element, exclusive, to be sorted + */ + private static void pushDown(double[] a, int p, double value, int low, int high) { + for (int k ;; a[p] = a[p = k]) { + k = (p << 1) - low + 2; // Index of the right child + + if (k > high) { + break; + } + if (k == high || a[k] < a[k - 1]) { + --k; + } + if (a[k] <= value) { + break; + } + } + a[p] = value; + } + +// #[class] + + /** + * This class implements parallel sorting. + */ + private static final class Sorter extends CountedCompleter { + + private static final long serialVersionUID = 123456789L; + + @SuppressWarnings("serial") + private final T a, b; + private final int low, size, offset, depth; + + @SuppressWarnings("unchecked") + private Sorter(T a, int parallelism, int low, int size, int depth) { + this.a = a; + this.low = low; + this.size = size; + this.offset = low; + + while ((parallelism >>= 2) > 0 && (size >>= 2) > 0) { + depth -= 2; + } + this.b = (T) tryAllocate(a.getClass(), this.size); + this.depth = b == null ? 0 : depth; + } + + private Sorter(CountedCompleter parent, + T a, T b, int low, int size, int offset, int depth) { + super(parent); + this.a = a; + this.b = b; + this.low = low; + this.size = size; + this.offset = offset; + this.depth = depth; + } + + @Override + @SuppressWarnings("unchecked") + public void compute() { + if (depth < 0) { + setPendingCount(2); + int half = size >> 1; + new Sorter<>(this, b, a, low, half, offset, depth + 1).fork(); + new Sorter<>(this, b, a, low + half, size - half, offset, depth + 1).compute(); + } else { + if (a instanceof int[]) { + sort((Sorter) this, (int[]) a, depth, low, low + size); + } else if (a instanceof long[]) { + sort((Sorter) this, (long[]) a, depth, low, low + size); + } else if (a instanceof float[]) { + sort((Sorter) this, (float[]) a, depth, low, low + size); + } else if (a instanceof double[]) { + sort((Sorter) this, (double[]) a, depth, low, low + size); + } else { + throw new IllegalArgumentException("Unknown array: " + a.getClass().getName()); + } + } + tryComplete(); + } + + @Override + public void onCompletion(CountedCompleter caller) { + if (depth < 0) { + int mi = low + (size >> 1); + boolean src = (depth & 1) == 0; + + new Merger<>(null, + a, + src ? low : low - offset, + b, + src ? low - offset : low, + src ? mi - offset : mi, + b, + src ? mi - offset : mi, + src ? low + size - offset : low + size + ).invoke(); + } + } + + private void fork(int depth, int low, int high) { + addToPendingCount(1); + new Sorter<>(this, a, b, low, high - low, offset, depth).fork(); + } + } + + /** + * This class implements parallel merging. + */ + private static final class Merger extends CountedCompleter { + + private static final long serialVersionUID = 123456789L; + + @SuppressWarnings("serial") + private final T dst, a1, a2; + private final int k, lo1, hi1, lo2, hi2; + + private Merger(CountedCompleter parent, T dst, int k, + T a1, int lo1, int hi1, T a2, int lo2, int hi2) { + super(parent); + this.dst = dst; + this.k = k; + this.a1 = a1; + this.lo1 = lo1; + this.hi1 = hi1; + this.a2 = a2; + this.lo2 = lo2; + this.hi2 = hi2; + } + + @Override + @SuppressWarnings("unchecked") + public void compute() { + if (dst instanceof int[]) { + mergeParts((Merger) this, (int[]) dst, k, + (int[]) a1, lo1, hi1, (int[]) a2, lo2, hi2); + } else if (dst instanceof long[]) { + mergeParts((Merger) this, (long[]) dst, k, + (long[]) a1, lo1, hi1, (long[]) a2, lo2, hi2); + } else if (dst instanceof float[]) { + mergeParts((Merger) this, (float[]) dst, k, + (float[]) a1, lo1, hi1, (float[]) a2, lo2, hi2); + } else if (dst instanceof double[]) { + mergeParts((Merger) this, (double[]) dst, k, + (double[]) a1, lo1, hi1, (double[]) a2, lo2, hi2); + } else { + throw new IllegalArgumentException("Unknown array: " + dst.getClass().getName()); + } + propagateCompletion(); + } + + private void fork(int k, int lo1, int hi1, int lo2, int hi2) { + addToPendingCount(1); + new Merger<>(this, dst, k, a1, lo1, hi1, a2, lo2, hi2).fork(); + } + } + + /** + * Tries to allocate additional buffer. + * + * @param clazz the given array class + * @param size the size of additional buffer + * @return {@code null} if requested size is too large or there is not enough memory, + * otherwise created buffer + */ + @SuppressWarnings("unchecked") + private static T tryAllocate(Class clazz, int size) { + try { + return size > MAX_BUFFER_SIZE ? null : + (T) U.allocateUninitializedArray(clazz.componentType(), size); + } catch (OutOfMemoryError e) { + return null; + } + } + + private static final Unsafe U = Unsafe.getUnsafe(); +} diff --git a/test/jdk/java/util/Arrays/Sorting.java b/test/jdk/java/util/Arrays/Sorting.java index e89496bb2e532..55ee8cd13736b 100644 --- a/test/jdk/java/util/Arrays/Sorting.java +++ b/test/jdk/java/util/Arrays/Sorting.java @@ -1,2016 +1,1798 @@ -/* - * Copyright (c) 2009, 2019, Oracle and/or its affiliates. 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. - * - * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @compile/module=java.base java/util/SortingHelper.java - * @bug 6880672 6896573 6899694 6976036 7013585 7018258 8003981 8226297 - * @build Sorting - * @run main Sorting -shortrun - * @summary Exercise Arrays.sort, Arrays.parallelSort - * - * @author Vladimir Yaroslavskiy - * @author Jon Bentley - * @author Josh Bloch - */ - -import java.io.PrintStream; -import java.util.Comparator; -import java.util.Random; -import java.util.SortingHelper; - -public class Sorting { - - private static final PrintStream out = System.out; - private static final PrintStream err = System.err; - - // Array lengths used in a long run (default) - private static final int[] LONG_RUN_LENGTHS = { - 1, 3, 8, 21, 55, 100, 1_000, 10_000, 100_000 }; - - // Array lengths used in a short run - private static final int[] SHORT_RUN_LENGTHS = { - 1, 8, 55, 100, 10_000 }; - - // Random initial values used in a long run (default) - private static final TestRandom[] LONG_RUN_RANDOMS = { - TestRandom.BABA, TestRandom.DEDA, TestRandom.C0FFEE }; - - // Random initial values used in a short run - private static final TestRandom[] SHORT_RUN_RANDOMS = { - TestRandom.C0FFEE }; - - // Constants used in subarray sorting - private static final int A380 = 0xA380; - private static final int B747 = 0xB747; - - private final SortingHelper sortingHelper; - private final TestRandom[] randoms; - private final int[] lengths; - private Object[] gold; - private Object[] test; - - public static void main(String[] args) { - long start = System.currentTimeMillis(); - boolean shortRun = args.length > 0 && args[0].equals("-shortrun"); - - int[] lengths = shortRun ? SHORT_RUN_LENGTHS : LONG_RUN_LENGTHS; - TestRandom[] randoms = shortRun ? SHORT_RUN_RANDOMS : LONG_RUN_RANDOMS; - - new Sorting(SortingHelper.DUAL_PIVOT_QUICKSORT, randoms, lengths).testCore(); - new Sorting(SortingHelper.PARALLEL_SORT, randoms, lengths).testCore(); - new Sorting(SortingHelper.HEAP_SORT, randoms, lengths).testBasic(); - new Sorting(SortingHelper.ARRAYS_SORT, randoms, lengths).testAll(); - new Sorting(SortingHelper.ARRAYS_PARALLEL_SORT, randoms, lengths).testAll(); - - long end = System.currentTimeMillis(); - out.format("PASSED in %d sec.\n", (end - start) / 1000); - } - - private Sorting(SortingHelper sortingHelper, TestRandom[] randoms, int[] lengths) { - this.sortingHelper = sortingHelper; - this.randoms = randoms; - this.lengths = lengths; - } - - private void testBasic() { - testEmptyArray(); - - for (int length : lengths) { - createData(length); - testBasic(length); - } - } - - private void testBasic(int length) { - for (TestRandom random : randoms) { - testWithInsertionSort(length, random); - testWithCheckSum(length, random); - testWithScrambling(length, random); - } - } - - private void testCore() { - for (int length : lengths) { - createData(length); - testCore(length); - } - } - - private void testCore(int length) { - testBasic(length); - - for (TestRandom random : randoms) { - testMergingSort(length, random); - testSubArray(length, random); - testNegativeZero(length, random); - testFloatingPointSorting(length, random); - } - } - - private void testAll() { - for (int length : lengths) { - createData(length); - testAll(length); - } - } - - private void testAll(int length) { - testCore(length); - - for (TestRandom random : randoms) { - testRange(length, random); - testStability(length, random); - } - } - - private void testEmptyArray() { - testEmptyAndNullIntArray(); - testEmptyAndNullLongArray(); - testEmptyAndNullByteArray(); - testEmptyAndNullCharArray(); - testEmptyAndNullShortArray(); - testEmptyAndNullFloatArray(); - testEmptyAndNullDoubleArray(); - } - - private void testStability(int length, TestRandom random) { - printTestName("Test stability", random, length); - - Pair[] a = build(length, random); - sortingHelper.sort(a); - checkSorted(a); - checkStable(a); - - a = build(length, random); - sortingHelper.sort(a, pairComparator); - checkSorted(a); - checkStable(a); - - out.println(); - } - - private void testEmptyAndNullIntArray() { - sortingHelper.sort(new int[] {}); - sortingHelper.sort(new int[] {}, 0, 0); - - try { - sortingHelper.sort(null); - } catch (NullPointerException expected) { - try { - sortingHelper.sort(null, 0, 0); - } catch (NullPointerException expected2) { - return; - } - fail(sortingHelper + "(int[],fromIndex,toIndex) shouldn't " + - "catch null array"); - } - fail(sortingHelper + "(int[]) shouldn't catch null array"); - } - - private void testEmptyAndNullLongArray() { - sortingHelper.sort(new long[] {}); - sortingHelper.sort(new long[] {}, 0, 0); - - try { - sortingHelper.sort(null); - } catch (NullPointerException expected) { - try { - sortingHelper.sort(null, 0, 0); - } catch (NullPointerException expected2) { - return; - } - fail(sortingHelper + "(long[],fromIndex,toIndex) shouldn't " + - "catch null array"); - } - fail(sortingHelper + "(long[]) shouldn't catch null array"); - } - - private void testEmptyAndNullByteArray() { - sortingHelper.sort(new byte[] {}); - sortingHelper.sort(new byte[] {}, 0, 0); - - try { - sortingHelper.sort(null); - } catch (NullPointerException expected) { - try { - sortingHelper.sort(null, 0, 0); - } catch (NullPointerException expected2) { - return; - } - fail(sortingHelper + "(byte[],fromIndex,toIndex) shouldn't " + - "catch null array"); - } - fail(sortingHelper + "(byte[]) shouldn't catch null array"); - } - - private void testEmptyAndNullCharArray() { - sortingHelper.sort(new char[] {}); - sortingHelper.sort(new char[] {}, 0, 0); - - try { - sortingHelper.sort(null); - } catch (NullPointerException expected) { - try { - sortingHelper.sort(null, 0, 0); - } catch (NullPointerException expected2) { - return; - } - fail(sortingHelper + "(char[],fromIndex,toIndex) shouldn't " + - "catch null array"); - } - fail(sortingHelper + "(char[]) shouldn't catch null array"); - } - - private void testEmptyAndNullShortArray() { - sortingHelper.sort(new short[] {}); - sortingHelper.sort(new short[] {}, 0, 0); - - try { - sortingHelper.sort(null); - } catch (NullPointerException expected) { - try { - sortingHelper.sort(null, 0, 0); - } catch (NullPointerException expected2) { - return; - } - fail(sortingHelper + "(short[],fromIndex,toIndex) shouldn't " + - "catch null array"); - } - fail(sortingHelper + "(short[]) shouldn't catch null array"); - } - - private void testEmptyAndNullFloatArray() { - sortingHelper.sort(new float[] {}); - sortingHelper.sort(new float[] {}, 0, 0); - - try { - sortingHelper.sort(null); - } catch (NullPointerException expected) { - try { - sortingHelper.sort(null, 0, 0); - } catch (NullPointerException expected2) { - return; - } - fail(sortingHelper + "(float[],fromIndex,toIndex) shouldn't " + - "catch null array"); - } - fail(sortingHelper + "(float[]) shouldn't catch null array"); - } - - private void testEmptyAndNullDoubleArray() { - sortingHelper.sort(new double[] {}); - sortingHelper.sort(new double[] {}, 0, 0); - - try { - sortingHelper.sort(null); - } catch (NullPointerException expected) { - try { - sortingHelper.sort(null, 0, 0); - } catch (NullPointerException expected2) { - return; - } - fail(sortingHelper + "(double[],fromIndex,toIndex) shouldn't " + - "catch null array"); - } - fail(sortingHelper + "(double[]) shouldn't catch null array"); - } - - private void testSubArray(int length, TestRandom random) { - if (length < 4) { - return; - } - for (int m = 1; m < length / 2; m <<= 1) { - int fromIndex = m; - int toIndex = length - m; - - prepareSubArray((int[]) gold[0], fromIndex, toIndex); - convertData(length); - - for (int i = 0; i < test.length; i++) { - printTestName("Test subarray", random, length, - ", m = " + m + ", " + getType(i)); - sortingHelper.sort(test[i], fromIndex, toIndex); - checkSubArray(test[i], fromIndex, toIndex); - } - } - out.println(); - } - - private void testRange(int length, TestRandom random) { - if (length < 2) { - return; - } - for (int m = 1; m < length; m <<= 1) { - for (int i = 1; i <= length; i++) { - ((int[]) gold[0]) [i - 1] = i % m + m % i; - } - convertData(length); - - for (int i = 0; i < test.length; i++) { - printTestName("Test range check", random, length, - ", m = " + m + ", " + getType(i)); - checkRange(test[i], m); - } - } - out.println(); - } - - private void checkSorted(Pair[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (a[i].getKey() > a[i + 1].getKey()) { - fail("Array is not sorted at " + i + "-th position: " + - a[i].getKey() + " and " + a[i + 1].getKey()); - } - } - } - - private void checkStable(Pair[] a) { - for (int i = 0; i < a.length / 4; ) { - int key1 = a[i].getKey(); - int value1 = a[i++].getValue(); - int key2 = a[i].getKey(); - int value2 = a[i++].getValue(); - int key3 = a[i].getKey(); - int value3 = a[i++].getValue(); - int key4 = a[i].getKey(); - int value4 = a[i++].getValue(); - - if (!(key1 == key2 && key2 == key3 && key3 == key4)) { - fail("Keys are different " + key1 + ", " + key2 + ", " + - key3 + ", " + key4 + " at position " + i); - } - if (!(value1 < value2 && value2 < value3 && value3 < value4)) { - fail("Sorting is not stable at position " + i + - ". Second values have been changed: " + value1 + ", " + - value2 + ", " + value3 + ", " + value4); - } - } - } - - private Pair[] build(int length, Random random) { - Pair[] a = new Pair[length * 4]; - - for (int i = 0; i < a.length; ) { - int key = random.nextInt(); - a[i++] = new Pair(key, 1); - a[i++] = new Pair(key, 2); - a[i++] = new Pair(key, 3); - a[i++] = new Pair(key, 4); - } - return a; - } - - private void testWithInsertionSort(int length, TestRandom random) { - if (length > 1000) { - return; - } - for (int m = 1; m <= length; m <<= 1) { - for (UnsortedBuilder builder : UnsortedBuilder.values()) { - builder.build((int[]) gold[0], m, random); - convertData(length); - - for (int i = 0; i < test.length; i++) { - printTestName("Test with insertion sort", random, length, - ", m = " + m + ", " + getType(i) + " " + builder); - sortingHelper.sort(test[i]); - sortByInsertionSort(gold[i]); - compare(test[i], gold[i]); - } - } - } - out.println(); - } - - private void testMergingSort(int length, TestRandom random) { - if (length < (4 << 10)) { // DualPivotQuicksort.MIN_TRY_MERGE_SIZE - return; - } - final int PERIOD = 50; - - for (int m = PERIOD - 2; m <= PERIOD + 2; m++) { - for (MergingBuilder builder : MergingBuilder.values()) { - builder.build((int[]) gold[0], m); - convertData(length); - - for (int i = 0; i < test.length; i++) { - printTestName("Test merging sort", random, length, - ", m = " + m + ", " + getType(i) + " " + builder); - sortingHelper.sort(test[i]); - checkSorted(test[i]); - } - } - } - out.println(); - } - - private void testWithCheckSum(int length, TestRandom random) { - for (int m = 1; m <= length; m <<= 1) { - for (UnsortedBuilder builder : UnsortedBuilder.values()) { - builder.build((int[]) gold[0], m, random); - convertData(length); - - for (int i = 0; i < test.length; i++) { - printTestName("Test with check sum", random, length, - ", m = " + m + ", " + getType(i) + " " + builder); - sortingHelper.sort(test[i]); - checkWithCheckSum(test[i], gold[i]); - } - } - } - out.println(); - } - - private void testWithScrambling(int length, TestRandom random) { - for (int m = 1; m <= length; m <<= 1) { - for (SortedBuilder builder : SortedBuilder.values()) { - builder.build((int[]) gold[0], m); - convertData(length); - - for (int i = 0; i < test.length; i++) { - printTestName("Test with scrambling", random, length, - ", m = " + m + ", " + getType(i) + " " + builder); - scramble(test[i], random); - sortingHelper.sort(test[i]); - compare(test[i], gold[i]); - } - } - } - out.println(); - } - - private void testNegativeZero(int length, TestRandom random) { - for (int i = 5; i < test.length; i++) { - printTestName("Test negative zero -0.0", random, length, " " + getType(i)); - - NegativeZeroBuilder builder = NegativeZeroBuilder.values() [i - 5]; - builder.build(test[i], random); - - sortingHelper.sort(test[i]); - checkNegativeZero(test[i]); - } - out.println(); - } - - private void testFloatingPointSorting(int length, TestRandom random) { - if (length < 2) { - return; - } - final int MAX = 13; - - for (int a = 0; a < MAX; a++) { - for (int g = 0; g < MAX; g++) { - for (int z = 0; z < MAX; z++) { - for (int n = 0; n < MAX; n++) { - for (int p = 0; p < MAX; p++) { - if (a + g + z + n + p != length) { - continue; - } - for (int i = 5; i < test.length; i++) { - printTestName("Test float-pointing sorting", random, length, - ", a = " + a + ", g = " + g + ", z = " + z + - ", n = " + n + ", p = " + p + ", " + getType(i)); - FloatingPointBuilder builder = FloatingPointBuilder.values()[i - 5]; - builder.build(gold[i], a, g, z, n, p, random); - copy(test[i], gold[i]); - scramble(test[i], random); - sortingHelper.sort(test[i]); - compare(test[i], gold[i], a, n, g); - } - } - } - } - } - } - - for (int m = 13; m > 4; m--) { - int t = length / m; - int g = t, z = t, n = t, p = t; - int a = length - g - z - n - p; - - for (int i = 5; i < test.length; i++) { - printTestName("Test float-pointing sorting", random, length, - ", a = " + a + ", g = " + g + ", z = " + z + - ", n = " + n + ", p = " + p + ", " + getType(i)); - FloatingPointBuilder builder = FloatingPointBuilder.values() [i - 5]; - builder.build(gold[i], a, g, z, n, p, random); - copy(test[i], gold[i]); - scramble(test[i], random); - sortingHelper.sort(test[i]); - compare(test[i], gold[i], a, n, g); - } - } - out.println(); - } - - private void prepareSubArray(int[] a, int fromIndex, int toIndex) { - for (int i = 0; i < fromIndex; i++) { - a[i] = A380; - } - int middle = (fromIndex + toIndex) >>> 1; - int k = 0; - - for (int i = fromIndex; i < middle; i++) { - a[i] = k++; - } - - for (int i = middle; i < toIndex; i++) { - a[i] = k--; - } - - for (int i = toIndex; i < a.length; i++) { - a[i] = B747; - } - } - - private void scramble(Object a, Random random) { - if (a instanceof int[]) { - scramble((int[]) a, random); - } else if (a instanceof long[]) { - scramble((long[]) a, random); - } else if (a instanceof byte[]) { - scramble((byte[]) a, random); - } else if (a instanceof char[]) { - scramble((char[]) a, random); - } else if (a instanceof short[]) { - scramble((short[]) a, random); - } else if (a instanceof float[]) { - scramble((float[]) a, random); - } else if (a instanceof double[]) { - scramble((double[]) a, random); - } else { - fail("Unknown type of array: " + a.getClass().getName()); - } - } - - private void scramble(int[] a, Random random) { - for (int i = 0; i < a.length * 7; i++) { - swap(a, random.nextInt(a.length), random.nextInt(a.length)); - } - } - - private void scramble(long[] a, Random random) { - for (int i = 0; i < a.length * 7; i++) { - swap(a, random.nextInt(a.length), random.nextInt(a.length)); - } - } - - private void scramble(byte[] a, Random random) { - for (int i = 0; i < a.length * 7; i++) { - swap(a, random.nextInt(a.length), random.nextInt(a.length)); - } - } - - private void scramble(char[] a, Random random) { - for (int i = 0; i < a.length * 7; i++) { - swap(a, random.nextInt(a.length), random.nextInt(a.length)); - } - } - - private void scramble(short[] a, Random random) { - for (int i = 0; i < a.length * 7; i++) { - swap(a, random.nextInt(a.length), random.nextInt(a.length)); - } - } - - private void scramble(float[] a, Random random) { - for (int i = 0; i < a.length * 7; i++) { - swap(a, random.nextInt(a.length), random.nextInt(a.length)); - } - } - - private void scramble(double[] a, Random random) { - for (int i = 0; i < a.length * 7; i++) { - swap(a, random.nextInt(a.length), random.nextInt(a.length)); - } - } - - private void swap(int[] a, int i, int j) { - int t = a[i]; a[i] = a[j]; a[j] = t; - } - - private void swap(long[] a, int i, int j) { - long t = a[i]; a[i] = a[j]; a[j] = t; - } - - private void swap(byte[] a, int i, int j) { - byte t = a[i]; a[i] = a[j]; a[j] = t; - } - - private void swap(char[] a, int i, int j) { - char t = a[i]; a[i] = a[j]; a[j] = t; - } - - private void swap(short[] a, int i, int j) { - short t = a[i]; a[i] = a[j]; a[j] = t; - } - - private void swap(float[] a, int i, int j) { - float t = a[i]; a[i] = a[j]; a[j] = t; - } - - private void swap(double[] a, int i, int j) { - double t = a[i]; a[i] = a[j]; a[j] = t; - } - - private void checkWithCheckSum(Object test, Object gold) { - checkSorted(test); - checkCheckSum(test, gold); - } - - private void fail(String message) { - err.format("\n*** TEST FAILED ***\n\n%s\n\n", message); - throw new RuntimeException("Test failed"); - } - - private void checkNegativeZero(Object a) { - if (a instanceof float[]) { - checkNegativeZero((float[]) a); - } else if (a instanceof double[]) { - checkNegativeZero((double[]) a); - } else { - fail("Unknown type of array: " + a.getClass().getName()); - } - } - - private void checkNegativeZero(float[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (Float.floatToRawIntBits(a[i]) == 0 && Float.floatToRawIntBits(a[i + 1]) < 0) { - fail(a[i] + " before " + a[i + 1] + " at position " + i); - } - } - } - - private void checkNegativeZero(double[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (Double.doubleToRawLongBits(a[i]) == 0 && Double.doubleToRawLongBits(a[i + 1]) < 0) { - fail(a[i] + " before " + a[i + 1] + " at position " + i); - } - } - } - - private void compare(Object a, Object b, int numNaN, int numNeg, int numNegZero) { - if (a instanceof float[]) { - compare((float[]) a, (float[]) b, numNaN, numNeg, numNegZero); - } else if (a instanceof double[]) { - compare((double[]) a, (double[]) b, numNaN, numNeg, numNegZero); - } else { - fail("Unknown type of array: " + a.getClass().getName()); - } - } - - private void compare(float[] a, float[] b, int numNaN, int numNeg, int numNegZero) { - for (int i = a.length - numNaN; i < a.length; i++) { - if (a[i] == a[i]) { - fail("There must be NaN instead of " + a[i] + " at position " + i); - } - } - final int NEGATIVE_ZERO = Float.floatToIntBits(-0.0f); - - for (int i = numNeg; i < numNeg + numNegZero; i++) { - if (NEGATIVE_ZERO != Float.floatToIntBits(a[i])) { - fail("There must be -0.0 instead of " + a[i] + " at position " + i); - } - } - - for (int i = 0; i < a.length - numNaN; i++) { - if (a[i] != b[i]) { - fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); - } - } - } - - private void compare(double[] a, double[] b, int numNaN, int numNeg, int numNegZero) { - for (int i = a.length - numNaN; i < a.length; i++) { - if (a[i] == a[i]) { - fail("There must be NaN instead of " + a[i] + " at position " + i); - } - } - final long NEGATIVE_ZERO = Double.doubleToLongBits(-0.0d); - - for (int i = numNeg; i < numNeg + numNegZero; i++) { - if (NEGATIVE_ZERO != Double.doubleToLongBits(a[i])) { - fail("There must be -0.0 instead of " + a[i] + " at position " + i); - } - } - - for (int i = 0; i < a.length - numNaN; i++) { - if (a[i] != b[i]) { - fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); - } - } - } - - private void compare(Object a, Object b) { - if (a instanceof int[]) { - compare((int[]) a, (int[]) b); - } else if (a instanceof long[]) { - compare((long[]) a, (long[]) b); - } else if (a instanceof byte[]) { - compare((byte[]) a, (byte[]) b); - } else if (a instanceof char[]) { - compare((char[]) a, (char[]) b); - } else if (a instanceof short[]) { - compare((short[]) a, (short[]) b); - } else if (a instanceof float[]) { - compare((float[]) a, (float[]) b); - } else if (a instanceof double[]) { - compare((double[]) a, (double[]) b); - } else { - fail("Unknown type of array: " + a.getClass().getName()); - } - } - - private void compare(int[] a, int[] b) { - for (int i = 0; i < a.length; i++) { - if (a[i] != b[i]) { - fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); - } - } - } - - private void compare(long[] a, long[] b) { - for (int i = 0; i < a.length; i++) { - if (a[i] != b[i]) { - fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); - } - } - } - - private void compare(byte[] a, byte[] b) { - for (int i = 0; i < a.length; i++) { - if (a[i] != b[i]) { - fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); - } - } - } - - private void compare(char[] a, char[] b) { - for (int i = 0; i < a.length; i++) { - if (a[i] != b[i]) { - fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); - } - } - } - - private void compare(short[] a, short[] b) { - for (int i = 0; i < a.length; i++) { - if (a[i] != b[i]) { - fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); - } - } - } - - private void compare(float[] a, float[] b) { - for (int i = 0; i < a.length; i++) { - if (a[i] != b[i]) { - fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); - } - } - } - - private void compare(double[] a, double[] b) { - for (int i = 0; i < a.length; i++) { - if (a[i] != b[i]) { - fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); - } - } - } - - private String getType(int i) { - Object a = test[i]; - - if (a instanceof int[]) { - return "INT "; - } - if (a instanceof long[]) { - return "LONG "; - } - if (a instanceof byte[]) { - return "BYTE "; - } - if (a instanceof char[]) { - return "CHAR "; - } - if (a instanceof short[]) { - return "SHORT "; - } - if (a instanceof float[]) { - return "FLOAT "; - } - if (a instanceof double[]) { - return "DOUBLE"; - } - fail("Unknown type of array: " + a.getClass().getName()); - return null; - } - - private void checkSorted(Object a) { - if (a instanceof int[]) { - checkSorted((int[]) a); - } else if (a instanceof long[]) { - checkSorted((long[]) a); - } else if (a instanceof byte[]) { - checkSorted((byte[]) a); - } else if (a instanceof char[]) { - checkSorted((char[]) a); - } else if (a instanceof short[]) { - checkSorted((short[]) a); - } else if (a instanceof float[]) { - checkSorted((float[]) a); - } else if (a instanceof double[]) { - checkSorted((double[]) a); - } else { - fail("Unknown type of array: " + a.getClass().getName()); - } - } - - private void checkSorted(int[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); - } - } - } - - private void checkSorted(long[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); - } - } - } - - private void checkSorted(byte[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); - } - } - } - - private void checkSorted(char[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); - } - } - } - - private void checkSorted(short[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); - } - } - } - - private void checkSorted(float[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); - } - } - } - - private void checkSorted(double[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); - } - } - } - - private void checkCheckSum(Object test, Object gold) { - if (checkSumXor(test) != checkSumXor(gold)) { - fail("Original and sorted arrays are not identical [^]"); - } - if (checkSumPlus(test) != checkSumPlus(gold)) { - fail("Original and sorted arrays are not identical [+]"); - } - } - - private int checkSumXor(Object a) { - if (a instanceof int[]) { - return checkSumXor((int[]) a); - } - if (a instanceof long[]) { - return checkSumXor((long[]) a); - } - if (a instanceof byte[]) { - return checkSumXor((byte[]) a); - } - if (a instanceof char[]) { - return checkSumXor((char[]) a); - } - if (a instanceof short[]) { - return checkSumXor((short[]) a); - } - if (a instanceof float[]) { - return checkSumXor((float[]) a); - } - if (a instanceof double[]) { - return checkSumXor((double[]) a); - } - fail("Unknown type of array: " + a.getClass().getName()); - return -1; - } - - private int checkSumXor(int[] a) { - int checkSum = 0; - - for (int e : a) { - checkSum ^= e; - } - return checkSum; - } - - private int checkSumXor(long[] a) { - long checkSum = 0; - - for (long e : a) { - checkSum ^= e; - } - return (int) checkSum; - } - - private int checkSumXor(byte[] a) { - byte checkSum = 0; - - for (byte e : a) { - checkSum ^= e; - } - return (int) checkSum; - } - - private int checkSumXor(char[] a) { - char checkSum = 0; - - for (char e : a) { - checkSum ^= e; - } - return (int) checkSum; - } - - private int checkSumXor(short[] a) { - short checkSum = 0; - - for (short e : a) { - checkSum ^= e; - } - return (int) checkSum; - } - - private int checkSumXor(float[] a) { - int checkSum = 0; - - for (float e : a) { - checkSum ^= (int) e; - } - return checkSum; - } - - private int checkSumXor(double[] a) { - int checkSum = 0; - - for (double e : a) { - checkSum ^= (int) e; - } - return checkSum; - } - - private int checkSumPlus(Object a) { - if (a instanceof int[]) { - return checkSumPlus((int[]) a); - } - if (a instanceof long[]) { - return checkSumPlus((long[]) a); - } - if (a instanceof byte[]) { - return checkSumPlus((byte[]) a); - } - if (a instanceof char[]) { - return checkSumPlus((char[]) a); - } - if (a instanceof short[]) { - return checkSumPlus((short[]) a); - } - if (a instanceof float[]) { - return checkSumPlus((float[]) a); - } - if (a instanceof double[]) { - return checkSumPlus((double[]) a); - } - fail("Unknown type of array: " + a.getClass().getName()); - return -1; - } - - private int checkSumPlus(int[] a) { - int checkSum = 0; - - for (int e : a) { - checkSum += e; - } - return checkSum; - } - - private int checkSumPlus(long[] a) { - long checkSum = 0; - - for (long e : a) { - checkSum += e; - } - return (int) checkSum; - } - - private int checkSumPlus(byte[] a) { - byte checkSum = 0; - - for (byte e : a) { - checkSum += e; - } - return (int) checkSum; - } - - private int checkSumPlus(char[] a) { - char checkSum = 0; - - for (char e : a) { - checkSum += e; - } - return (int) checkSum; - } - - private int checkSumPlus(short[] a) { - short checkSum = 0; - - for (short e : a) { - checkSum += e; - } - return (int) checkSum; - } - - private int checkSumPlus(float[] a) { - int checkSum = 0; - - for (float e : a) { - checkSum += (int) e; - } - return checkSum; - } - - private int checkSumPlus(double[] a) { - int checkSum = 0; - - for (double e : a) { - checkSum += (int) e; - } - return checkSum; - } - - private void sortByInsertionSort(Object a) { - if (a instanceof int[]) { - sortByInsertionSort((int[]) a); - } else if (a instanceof long[]) { - sortByInsertionSort((long[]) a); - } else if (a instanceof byte[]) { - sortByInsertionSort((byte[]) a); - } else if (a instanceof char[]) { - sortByInsertionSort((char[]) a); - } else if (a instanceof short[]) { - sortByInsertionSort((short[]) a); - } else if (a instanceof float[]) { - sortByInsertionSort((float[]) a); - } else if (a instanceof double[]) { - sortByInsertionSort((double[]) a); - } else { - fail("Unknown type of array: " + a.getClass().getName()); - } - } - - private void sortByInsertionSort(int[] a) { - for (int j, i = 1; i < a.length; i++) { - int ai = a[i]; - - for (j = i - 1; j >= 0 && ai < a[j]; j--) { - a[j + 1] = a[j]; - } - a[j + 1] = ai; - } - } - - private void sortByInsertionSort(long[] a) { - for (int j, i = 1; i < a.length; i++) { - long ai = a[i]; - - for (j = i - 1; j >= 0 && ai < a[j]; j--) { - a[j + 1] = a[j]; - } - a[j + 1] = ai; - } - } - - private void sortByInsertionSort(byte[] a) { - for (int j, i = 1; i < a.length; i++) { - byte ai = a[i]; - - for (j = i - 1; j >= 0 && ai < a[j]; j--) { - a[j + 1] = a[j]; - } - a[j + 1] = ai; - } - } - - private void sortByInsertionSort(char[] a) { - for (int j, i = 1; i < a.length; i++) { - char ai = a[i]; - - for (j = i - 1; j >= 0 && ai < a[j]; j--) { - a[j + 1] = a[j]; - } - a[j + 1] = ai; - } - } - - private void sortByInsertionSort(short[] a) { - for (int j, i = 1; i < a.length; i++) { - short ai = a[i]; - - for (j = i - 1; j >= 0 && ai < a[j]; j--) { - a[j + 1] = a[j]; - } - a[j + 1] = ai; - } - } - - private void sortByInsertionSort(float[] a) { - for (int j, i = 1; i < a.length; i++) { - float ai = a[i]; - - for (j = i - 1; j >= 0 && ai < a[j]; j--) { - a[j + 1] = a[j]; - } - a[j + 1] = ai; - } - } - - private void sortByInsertionSort(double[] a) { - for (int j, i = 1; i < a.length; i++) { - double ai = a[i]; - - for (j = i - 1; j >= 0 && ai < a[j]; j--) { - a[j + 1] = a[j]; - } - a[j + 1] = ai; - } - } - - private void checkSubArray(Object a, int fromIndex, int toIndex) { - if (a instanceof int[]) { - checkSubArray((int[]) a, fromIndex, toIndex); - } else if (a instanceof long[]) { - checkSubArray((long[]) a, fromIndex, toIndex); - } else if (a instanceof byte[]) { - checkSubArray((byte[]) a, fromIndex, toIndex); - } else if (a instanceof char[]) { - checkSubArray((char[]) a, fromIndex, toIndex); - } else if (a instanceof short[]) { - checkSubArray((short[]) a, fromIndex, toIndex); - } else if (a instanceof float[]) { - checkSubArray((float[]) a, fromIndex, toIndex); - } else if (a instanceof double[]) { - checkSubArray((double[]) a, fromIndex, toIndex); - } else { - fail("Unknown type of array: " + a.getClass().getName()); - } - } - - private void checkSubArray(int[] a, int fromIndex, int toIndex) { - for (int i = 0; i < fromIndex; i++) { - if (a[i] != A380) { - fail("Range sort changes left element at position " + i + hex(a[i], A380)); - } - } - - for (int i = fromIndex; i < toIndex - 1; i++) { - if (a[i] > a[i + 1]) { - fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); - } - } - - for (int i = toIndex; i < a.length; i++) { - if (a[i] != B747) { - fail("Range sort changes right element at position " + i + hex(a[i], B747)); - } - } - } - - private void checkSubArray(long[] a, int fromIndex, int toIndex) { - for (int i = 0; i < fromIndex; i++) { - if (a[i] != (long) A380) { - fail("Range sort changes left element at position " + i + hex(a[i], A380)); - } - } - - for (int i = fromIndex; i < toIndex - 1; i++) { - if (a[i] > a[i + 1]) { - fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); - } - } - - for (int i = toIndex; i < a.length; i++) { - if (a[i] != (long) B747) { - fail("Range sort changes right element at position " + i + hex(a[i], B747)); - } - } - } - - private void checkSubArray(byte[] a, int fromIndex, int toIndex) { - for (int i = 0; i < fromIndex; i++) { - if (a[i] != (byte) A380) { - fail("Range sort changes left element at position " + i + hex(a[i], A380)); - } - } - - for (int i = fromIndex; i < toIndex - 1; i++) { - if (a[i] > a[i + 1]) { - fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); - } - } - - for (int i = toIndex; i < a.length; i++) { - if (a[i] != (byte) B747) { - fail("Range sort changes right element at position " + i + hex(a[i], B747)); - } - } - } - - private void checkSubArray(char[] a, int fromIndex, int toIndex) { - for (int i = 0; i < fromIndex; i++) { - if (a[i] != (char) A380) { - fail("Range sort changes left element at position " + i + hex(a[i], A380)); - } - } - - for (int i = fromIndex; i < toIndex - 1; i++) { - if (a[i] > a[i + 1]) { - fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); - } - } - - for (int i = toIndex; i < a.length; i++) { - if (a[i] != (char) B747) { - fail("Range sort changes right element at position " + i + hex(a[i], B747)); - } - } - } - - private void checkSubArray(short[] a, int fromIndex, int toIndex) { - for (int i = 0; i < fromIndex; i++) { - if (a[i] != (short) A380) { - fail("Range sort changes left element at position " + i + hex(a[i], A380)); - } - } - - for (int i = fromIndex; i < toIndex - 1; i++) { - if (a[i] > a[i + 1]) { - fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); - } - } - - for (int i = toIndex; i < a.length; i++) { - if (a[i] != (short) B747) { - fail("Range sort changes right element at position " + i + hex(a[i], B747)); - } - } - } - - private void checkSubArray(float[] a, int fromIndex, int toIndex) { - for (int i = 0; i < fromIndex; i++) { - if (a[i] != (float) A380) { - fail("Range sort changes left element at position " + i + hex((long) a[i], A380)); - } - } - - for (int i = fromIndex; i < toIndex - 1; i++) { - if (a[i] > a[i + 1]) { - fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); - } - } - - for (int i = toIndex; i < a.length; i++) { - if (a[i] != (float) B747) { - fail("Range sort changes right element at position " + i + hex((long) a[i], B747)); - } - } - } - - private void checkSubArray(double[] a, int fromIndex, int toIndex) { - for (int i = 0; i < fromIndex; i++) { - if (a[i] != (double) A380) { - fail("Range sort changes left element at position " + i + hex((long) a[i], A380)); - } - } - - for (int i = fromIndex; i < toIndex - 1; i++) { - if (a[i] > a[i + 1]) { - fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); - } - } - - for (int i = toIndex; i < a.length; i++) { - if (a[i] != (double) B747) { - fail("Range sort changes right element at position " + i + hex((long) a[i], B747)); - } - } - } - - private void checkRange(Object a, int m) { - if (a instanceof int[]) { - checkRange((int[]) a, m); - } else if (a instanceof long[]) { - checkRange((long[]) a, m); - } else if (a instanceof byte[]) { - checkRange((byte[]) a, m); - } else if (a instanceof char[]) { - checkRange((char[]) a, m); - } else if (a instanceof short[]) { - checkRange((short[]) a, m); - } else if (a instanceof float[]) { - checkRange((float[]) a, m); - } else if (a instanceof double[]) { - checkRange((double[]) a, m); - } else { - fail("Unknown type of array: " + a.getClass().getName()); - } - } - - private void checkRange(int[] a, int m) { - try { - sortingHelper.sort(a, m + 1, m); - fail(sortingHelper + " does not throw IllegalArgumentException " + - "as expected: fromIndex = " + (m + 1) + " toIndex = " + m); - } catch (IllegalArgumentException iae) { - try { - sortingHelper.sort(a, -m, a.length); - fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + - "as expected: fromIndex = " + (-m)); - } catch (ArrayIndexOutOfBoundsException aoe) { - try { - sortingHelper.sort(a, 0, a.length + m); - fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + - "as expected: toIndex = " + (a.length + m)); - } catch (ArrayIndexOutOfBoundsException expected) {} - } - } - } - - private void checkRange(long[] a, int m) { - try { - sortingHelper.sort(a, m + 1, m); - fail(sortingHelper + " does not throw IllegalArgumentException " + - "as expected: fromIndex = " + (m + 1) + " toIndex = " + m); - } catch (IllegalArgumentException iae) { - try { - sortingHelper.sort(a, -m, a.length); - fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + - "as expected: fromIndex = " + (-m)); - } catch (ArrayIndexOutOfBoundsException aoe) { - try { - sortingHelper.sort(a, 0, a.length + m); - fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + - "as expected: toIndex = " + (a.length + m)); - } catch (ArrayIndexOutOfBoundsException expected) {} - } - } - } - - private void checkRange(byte[] a, int m) { - try { - sortingHelper.sort(a, m + 1, m); - fail(sortingHelper + " does not throw IllegalArgumentException " + - "as expected: fromIndex = " + (m + 1) + " toIndex = " + m); - } catch (IllegalArgumentException iae) { - try { - sortingHelper.sort(a, -m, a.length); - fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + - "as expected: fromIndex = " + (-m)); - } catch (ArrayIndexOutOfBoundsException aoe) { - try { - sortingHelper.sort(a, 0, a.length + m); - fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + - "as expected: toIndex = " + (a.length + m)); - } catch (ArrayIndexOutOfBoundsException expected) {} - } - } - } - - private void checkRange(char[] a, int m) { - try { - sortingHelper.sort(a, m + 1, m); - fail(sortingHelper + " does not throw IllegalArgumentException " + - "as expected: fromIndex = " + (m + 1) + " toIndex = " + m); - } catch (IllegalArgumentException iae) { - try { - sortingHelper.sort(a, -m, a.length); - fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + - "as expected: fromIndex = " + (-m)); - } catch (ArrayIndexOutOfBoundsException aoe) { - try { - sortingHelper.sort(a, 0, a.length + m); - fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + - "as expected: toIndex = " + (a.length + m)); - } catch (ArrayIndexOutOfBoundsException expected) {} - } - } - } - - private void checkRange(short[] a, int m) { - try { - sortingHelper.sort(a, m + 1, m); - fail(sortingHelper + " does not throw IllegalArgumentException " + - "as expected: fromIndex = " + (m + 1) + " toIndex = " + m); - } catch (IllegalArgumentException iae) { - try { - sortingHelper.sort(a, -m, a.length); - fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + - "as expected: fromIndex = " + (-m)); - } catch (ArrayIndexOutOfBoundsException aoe) { - try { - sortingHelper.sort(a, 0, a.length + m); - fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + - "as expected: toIndex = " + (a.length + m)); - } catch (ArrayIndexOutOfBoundsException expected) {} - } - } - } - - private void checkRange(float[] a, int m) { - try { - sortingHelper.sort(a, m + 1, m); - fail(sortingHelper + " does not throw IllegalArgumentException " + - "as expected: fromIndex = " + (m + 1) + " toIndex = " + m); - } catch (IllegalArgumentException iae) { - try { - sortingHelper.sort(a, -m, a.length); - fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + - "as expected: fromIndex = " + (-m)); - } catch (ArrayIndexOutOfBoundsException aoe) { - try { - sortingHelper.sort(a, 0, a.length + m); - fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + - "as expected: toIndex = " + (a.length + m)); - } catch (ArrayIndexOutOfBoundsException expected) {} - } - } - } - - private void checkRange(double[] a, int m) { - try { - sortingHelper.sort(a, m + 1, m); - fail(sortingHelper + " does not throw IllegalArgumentException " + - "as expected: fromIndex = " + (m + 1) + " toIndex = " + m); - } catch (IllegalArgumentException iae) { - try { - sortingHelper.sort(a, -m, a.length); - fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + - "as expected: fromIndex = " + (-m)); - } catch (ArrayIndexOutOfBoundsException aoe) { - try { - sortingHelper.sort(a, 0, a.length + m); - fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + - "as expected: toIndex = " + (a.length + m)); - } catch (ArrayIndexOutOfBoundsException expected) {} - } - } - } - - private void copy(Object dst, Object src) { - if (src instanceof float[]) { - copy((float[]) dst, (float[]) src); - } else if (src instanceof double[]) { - copy((double[]) dst, (double[]) src); - } else { - fail("Unknown type of array: " + src.getClass().getName()); - } - } - - private void copy(float[] dst, float[] src) { - System.arraycopy(src, 0, dst, 0, src.length); - } - - private void copy(double[] dst, double[] src) { - System.arraycopy(src, 0, dst, 0, src.length); - } - - private void printTestName(String test, TestRandom random, int length) { - printTestName(test, random, length, ""); - } - - private void createData(int length) { - gold = new Object[] { - new int[length], new long[length], - new byte[length], new char[length], new short[length], - new float[length], new double[length] - }; - - test = new Object[] { - new int[length], new long[length], - new byte[length], new char[length], new short[length], - new float[length], new double[length] - }; - } - - private void convertData(int length) { - for (int i = 1; i < gold.length; i++) { - TypeConverter converter = TypeConverter.values()[i - 1]; - converter.convert((int[])gold[0], gold[i]); - } - - for (int i = 0; i < gold.length; i++) { - System.arraycopy(gold[i], 0, test[i], 0, length); - } - } - - private String hex(long a, int b) { - return ": " + Long.toHexString(a) + ", must be " + Integer.toHexString(b); - } - - private void printTestName(String test, TestRandom random, int length, String message) { - out.println( "[" + sortingHelper + "] '" + test + - "' length = " + length + ", random = " + random + message); - } - - private static enum TypeConverter { - LONG { - void convert(int[] src, Object dst) { - long[] b = (long[]) dst; - - for (int i = 0; i < src.length; i++) { - b[i] = (long) src[i]; - } - } - }, - - BYTE { - void convert(int[] src, Object dst) { - byte[] b = (byte[]) dst; - - for (int i = 0; i < src.length; i++) { - b[i] = (byte) src[i]; - } - } - }, - - CHAR { - void convert(int[] src, Object dst) { - char[] b = (char[]) dst; - - for (int i = 0; i < src.length; i++) { - b[i] = (char) src[i]; - } - } - }, - - SHORT { - void convert(int[] src, Object dst) { - short[] b = (short[]) dst; - - for (int i = 0; i < src.length; i++) { - b[i] = (short) src[i]; - } - } - }, - - FLOAT { - void convert(int[] src, Object dst) { - float[] b = (float[]) dst; - - for (int i = 0; i < src.length; i++) { - b[i] = (float) src[i]; - } - } - }, - - DOUBLE { - void convert(int[] src, Object dst) { - double[] b = (double[]) dst; - - for (int i = 0; i < src.length; i++) { - b[i] = (double) src[i]; - } - } - }; - - abstract void convert(int[] src, Object dst); - } - - private static enum SortedBuilder { - STEPS { - void build(int[] a, int m) { - for (int i = 0; i < m; i++) { - a[i] = 0; - } - - for (int i = m; i < a.length; i++) { - a[i] = 1; - } - } - }; - - abstract void build(int[] a, int m); - } - - private static enum UnsortedBuilder { - RANDOM { - void build(int[] a, int m, Random random) { - for (int i = 0; i < a.length; i++) { - a[i] = random.nextInt(); - } - } - }, - - ASCENDING { - void build(int[] a, int m, Random random) { - for (int i = 0; i < a.length; i++) { - a[i] = m + i; - } - } - }, - - DESCENDING { - void build(int[] a, int m, Random random) { - for (int i = 0; i < a.length; i++) { - a[i] = a.length - m - i; - } - } - }, - - EQUAL { - void build(int[] a, int m, Random random) { - for (int i = 0; i < a.length; i++) { - a[i] = m; - } - } - }, - - SAW { - void build(int[] a, int m, Random random) { - int incCount = 1; - int decCount = a.length; - int i = 0; - int period = m--; - - while (true) { - for (int k = 1; k <= period; k++) { - if (i >= a.length) { - return; - } - a[i++] = incCount++; - } - period += m; - - for (int k = 1; k <= period; k++) { - if (i >= a.length) { - return; - } - a[i++] = decCount--; - } - period += m; - } - } - }, - - REPEATED { - void build(int[] a, int m, Random random) { - for (int i = 0; i < a.length; i++) { - a[i] = i % m; - } - } - }, - - DUPLICATED { - void build(int[] a, int m, Random random) { - for (int i = 0; i < a.length; i++) { - a[i] = random.nextInt(m); - } - } - }, - - ORGAN_PIPES { - void build(int[] a, int m, Random random) { - int middle = a.length / (m + 1); - - for (int i = 0; i < middle; i++) { - a[i] = i; - } - - for (int i = middle; i < a.length; i++) { - a[i] = a.length - i - 1; - } - } - }, - - STAGGER { - void build(int[] a, int m, Random random) { - for (int i = 0; i < a.length; i++) { - a[i] = (i * m + i) % a.length; - } - } - }, - - PLATEAU { - void build(int[] a, int m, Random random) { - for (int i = 0; i < a.length; i++) { - a[i] = Math.min(i, m); - } - } - }, - - SHUFFLE { - void build(int[] a, int m, Random random) { - int x = 0, y = 0; - - for (int i = 0; i < a.length; i++) { - a[i] = random.nextBoolean() ? (x += 2) : (y += 2); - } - } - }, - - LATCH { - void build(int[] a, int m, Random random) { - int max = a.length / m; - max = max < 2 ? 2 : max; - - for (int i = 0; i < a.length; i++) { - a[i] = i % max; - } - } - }; - - abstract void build(int[] a, int m, Random random); - } - - private static enum MergingBuilder { - ASCENDING { - void build(int[] a, int m) { - int period = a.length / m; - int v = 1, i = 0; - - for (int k = 0; k < m; k++) { - v = 1; - - for (int p = 0; p < period; p++) { - a[i++] = v++; - } - } - - for (int j = i; j < a.length - 1; j++) { - a[j] = v++; - } - - a[a.length - 1] = 0; - } - }, - - DESCENDING { - void build(int[] a, int m) { - int period = a.length / m; - int v = -1, i = 0; - - for (int k = 0; k < m; k++) { - v = -1; - - for (int p = 0; p < period; p++) { - a[i++] = v--; - } - } - - for (int j = i; j < a.length - 1; j++) { - a[j] = v--; - } - - a[a.length - 1] = 0; - } - }, - - POINT { - void build(int[] a, int m) { - for (int i = 0; i < a.length; i++) { - a[i] = 0; - } - a[a.length / 2] = m; - } - }, - - LINE { - void build(int[] a, int m) { - for (int i = 0; i < a.length; i++) { - a[i] = i; - } - reverse(a, 0, a.length - 1); - } - }, - - PEARL { - void build(int[] a, int m) { - for (int i = 0; i < a.length; i++) { - a[i] = i; - } - reverse(a, 0, 2); - } - }, - - RING { - void build(int[] a, int m) { - int k1 = a.length / 3; - int k2 = a.length / 3 * 2; - int level = a.length / 3; - - for (int i = 0, k = level; i < k1; i++) { - a[i] = k--; - } - - for (int i = k1; i < k2; i++) { - a[i] = 0; - } - - for (int i = k2, k = level; i < a.length; i++) { - a[i] = k--; - } - } - }; - - abstract void build(int[] a, int m); - - private static void reverse(int[] a, int lo, int hi) { - for (--hi; lo < hi; ) { - int tmp = a[lo]; - a[lo++] = a[hi]; - a[hi--] = tmp; - } - } - } - - private static enum NegativeZeroBuilder { - FLOAT { - void build(Object o, Random random) { - float[] a = (float[]) o; - - for (int i = 0; i < a.length; i++) { - a[i] = random.nextBoolean() ? -0.0f : 0.0f; - } - } - }, - - DOUBLE { - void build(Object o, Random random) { - double[] a = (double[]) o; - - for (int i = 0; i < a.length; i++) { - a[i] = random.nextBoolean() ? -0.0d : 0.0d; - } - } - }; - - abstract void build(Object o, Random random); - } - - private static enum FloatingPointBuilder { - FLOAT { - void build(Object o, int a, int g, int z, int n, int p, Random random) { - float negativeValue = -random.nextFloat(); - float positiveValue = random.nextFloat(); - float[] x = (float[]) o; - int fromIndex = 0; - - writeValue(x, negativeValue, fromIndex, n); - fromIndex += n; - - writeValue(x, -0.0f, fromIndex, g); - fromIndex += g; - - writeValue(x, 0.0f, fromIndex, z); - fromIndex += z; - - writeValue(x, positiveValue, fromIndex, p); - fromIndex += p; - - writeValue(x, Float.NaN, fromIndex, a); - } - }, - - DOUBLE { - void build(Object o, int a, int g, int z, int n, int p, Random random) { - double negativeValue = -random.nextFloat(); - double positiveValue = random.nextFloat(); - double[] x = (double[]) o; - int fromIndex = 0; - - writeValue(x, negativeValue, fromIndex, n); - fromIndex += n; - - writeValue(x, -0.0d, fromIndex, g); - fromIndex += g; - - writeValue(x, 0.0d, fromIndex, z); - fromIndex += z; - - writeValue(x, positiveValue, fromIndex, p); - fromIndex += p; - - writeValue(x, Double.NaN, fromIndex, a); - } - }; - - abstract void build(Object o, int a, int g, int z, int n, int p, Random random); - - private static void writeValue(float[] a, float value, int fromIndex, int count) { - for (int i = fromIndex; i < fromIndex + count; i++) { - a[i] = value; - } - } - - private static void writeValue(double[] a, double value, int fromIndex, int count) { - for (int i = fromIndex; i < fromIndex + count; i++) { - a[i] = value; - } - } - } - - private static Comparator pairComparator = new Comparator() { - - @Override - public int compare(Pair p1, Pair p2) { - return p1.compareTo(p2); - } - }; - - private static class Pair implements Comparable { - - private Pair(int key, int value) { - this.key = key; - this.value = value; - } - - int getKey() { - return key; - } - - int getValue() { - return value; - } - - @Override - public int compareTo(Pair pair) { - return Integer.compare(key, pair.key); - } - - @Override - public String toString() { - return "(" + key + ", " + value + ")"; - } - - private int key; - private int value; - } - - private static class TestRandom extends Random { - - private static final TestRandom BABA = new TestRandom(0xBABA); - private static final TestRandom DEDA = new TestRandom(0xDEDA); - private static final TestRandom C0FFEE = new TestRandom(0xC0FFEE); - - private TestRandom(long seed) { - super(seed); - this.seed = Long.toHexString(seed).toUpperCase(); - } - - @Override - public String toString() { - return seed; - } - - private String seed; - } -} +/* + * Copyright (c) 2009, 2023, Oracle and/or its affiliates. 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. + * + * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @compile/module=java.base java/util/SortingHelper.java + * @bug 6880672 6896573 6899694 6976036 7013585 7018258 8003981 8226297 8266431 + * @build Sorting + * @run main Sorting -shortrun + * @summary Exercise Arrays.sort, Arrays.parallelSort + * + * @author Vladimir Yaroslavskiy + * @author Jon Bentley + * @author Josh Bloch + */ + +import java.io.PrintStream; +import java.util.Arrays; +import java.util.Random; +import java.util.SortingHelper; + +public class Sorting { + + private static final PrintStream out = System.out; + private static final PrintStream err = System.err; + + // Lengths of arrays for short run + private static final int[] SHORT_RUN_LENGTHS = + { 1, 2, 14, 100, 500, 1_000, 10_000 }; + + // Lengths of arrays for long run (default) + private static final int[] LONG_RUN_LENGTHS = + { 1, 2, 14, 100, 500, 1_000, 10_000, 50_000 }; + + // Initial random values for short run + private static final TestRandom[] SHORT_RUN_RANDOMS = + { TestRandom.C0FFEE }; + + // Initial random values for long run (default) + private static final TestRandom[] LONG_RUN_RANDOMS = + { TestRandom.DEDA, TestRandom.BABA, TestRandom.C0FFEE }; + + // Constant to fill the left part of array + private static final int A380 = 0xA380; + + // Constant to fill the right part of array + private static final int B747 = 0xB747; + + private final SortingHelper sortingHelper; + private final TestRandom[] randoms; + private final int[] lengths; + private final boolean fix; + private Object[] gold; + private Object[] test; + + public static void main(String[] args) { + long start = System.currentTimeMillis(); + boolean shortRun = args.length > 0 && args[0].equals("-shortrun"); + + int[] lengths = shortRun ? SHORT_RUN_LENGTHS : LONG_RUN_LENGTHS; + TestRandom[] randoms = shortRun ? SHORT_RUN_RANDOMS : LONG_RUN_RANDOMS; + + new Sorting(SortingHelper.MIXED_INSERTION_SORT, randoms).testBase(); + new Sorting(SortingHelper.MERGING_SORT, randoms, lengths).testStructured(512); + new Sorting(SortingHelper.HEAP_SORT, randoms, lengths).testBase(); + new Sorting(SortingHelper.RADIX_SORT, randoms, lengths).testCore(); + new Sorting(SortingHelper.DUAL_PIVOT_QUICKSORT, randoms, lengths).testCore(); + new Sorting(SortingHelper.PARALLEL_SORT, randoms, lengths).testCore(); + new Sorting(SortingHelper.ARRAYS_SORT, randoms, lengths).testAll(); + new Sorting(SortingHelper.ARRAYS_PARALLEL_SORT, randoms, lengths).testAll(); + + long end = System.currentTimeMillis(); + out.format("PASSED in %d sec.\n", (end - start) / 1_000); + } + + private Sorting(SortingHelper sortingHelper, TestRandom[] randoms) { + this(sortingHelper, randoms, SHORT_RUN_LENGTHS, true); + } + + private Sorting(SortingHelper sortingHelper, TestRandom[] randoms, int[] lengths) { + this(sortingHelper, randoms, lengths, false); + } + + private Sorting(SortingHelper sortingHelper, TestRandom[] randoms, int[] lengths, boolean fix) { + this.sortingHelper = sortingHelper; + this.randoms = randoms; + this.lengths = lengths; + this.fix = fix; + } + + private void testBase() { + testStructured(0); + testEmptyArray(); + + for (int length : lengths) { + createData(length); + testSubArray(length); + + for (TestRandom random : randoms) { + testWithCheckSum(length, random); + testWithScrambling(length, random); + testWithInsertionSort(length, random); + } + } + } + + private void testCore() { + testBase(); + + for (int length : lengths) { + createData(length); + + for (TestRandom random : randoms) { + testNegativeZero(length, random); + testFloatingPointSorting(length, random); + } + } + } + + private void testAll() { + testCore(); + + for (int length : lengths) { + createData(length); + testRange(length); + } + } + + private void testStructured(int min) { + for (int length : lengths) { + createData(length); + testStructured(length, min); + } + } + + private void testEmptyArray() { + sortingHelper.sort(new int[] {}); + sortingHelper.sort(new int[] {}, 0, 0); + + sortingHelper.sort(new long[] {}); + sortingHelper.sort(new long[] {}, 0, 0); + + sortingHelper.sort(new byte[] {}); + sortingHelper.sort(new byte[] {}, 0, 0); + + sortingHelper.sort(new char[] {}); + sortingHelper.sort(new char[] {}, 0, 0); + + sortingHelper.sort(new short[] {}); + sortingHelper.sort(new short[] {}, 0, 0); + + sortingHelper.sort(new float[] {}); + sortingHelper.sort(new float[] {}, 0, 0); + + sortingHelper.sort(new double[] {}); + sortingHelper.sort(new double[] {}, 0, 0); + } + + private void testSubArray(int length) { + if (fix || length < 4) { + return; + } + for (int m = 1; m < length / 2; m <<= 1) { + int toIndex = length - m; + + prepareSubArray((int[]) gold[0], m, toIndex); + convertData(length); + + for (int i = 0; i < test.length; ++i) { + printTestName("Test subarray", length, + ", m = " + m + ", " + getType(i)); + sortingHelper.sort(test[i], m, toIndex); + checkSubArray(test[i], m, toIndex); + } + } + out.println(); + } + + private void testRange(int length) { + for (int m = 1; m < length; m <<= 1) { + for (int i = 1; i <= length; ++i) { + ((int[]) gold[0])[i - 1] = i % m + m % i; + } + convertData(length); + + for (int i = 0; i < test.length; ++i) { + printTestName("Test range check", length, + ", m = " + m + ", " + getType(i)); + checkRange(test[i], m); + } + } + out.println(); + } + + private void testWithInsertionSort(int length, TestRandom random) { + if (length > 1_000) { + return; + } + for (int m = 1; m <= length; m <<= 1) { + for (UnsortedBuilder builder : UnsortedBuilder.values()) { + builder.build((int[]) gold[0], m, random); + convertData(length); + + for (int i = 0; i < test.length; ++i) { + printTestName("Test with insertion sort", random, length, + ", m = " + m + ", " + getType(i) + " " + builder); + sortingHelper.sort(test[i]); + sortByInsertionSort(gold[i]); + checkSorted(gold[i]); + compare(test[i], gold[i]); + } + } + } + out.println(); + } + + private void testStructured(int length, int min) { + if (length < min) { + return; + } + for (int m = 1; m < 8; ++m) { + for (StructuredBuilder builder : StructuredBuilder.values()) { + builder.build((int[]) gold[0], m); + convertData(length); + + for (int i = 0; i < test.length; ++i) { + printTestName("Test structured", length, + ", m = " + m + ", " + getType(i) + " " + builder); + sortingHelper.sort(test[i]); + checkSorted(test[i]); + } + } + } + out.println(); + } + + private void testWithCheckSum(int length, TestRandom random) { + if (length > 1_000) { + return; + } + for (int m = 1; m <= length; m <<= 1) { + for (UnsortedBuilder builder : UnsortedBuilder.values()) { + builder.build((int[]) gold[0], m, random); + convertData(length); + + for (int i = 0; i < test.length; ++i) { + printTestName("Test with check sum", random, length, + ", m = " + m + ", " + getType(i) + " " + builder); + sortingHelper.sort(test[i]); + checkWithCheckSum(test[i], gold[i]); + } + } + } + out.println(); + } + + private void testWithScrambling(int length, TestRandom random) { + if (fix) { + return; + } + for (int m = 1; m <= length; m <<= 1) { + for (SortedBuilder builder : SortedBuilder.values()) { + builder.build((int[]) gold[0], m); + convertData(length); + + for (int i = 0; i < test.length; ++i) { + printTestName("Test with scrambling", random, length, + ", m = " + m + ", " + getType(i) + " " + builder); + scramble(test[i], random); + sortingHelper.sort(test[i]); + compare(test[i], gold[i]); + } + } + } + out.println(); + } + + private void testNegativeZero(int length, TestRandom random) { + for (int i = 5; i < test.length; ++i) { + printTestName("Test negative zero -0.0", random, length, " " + getType(i)); + + NegativeZeroBuilder builder = NegativeZeroBuilder.values()[i - 5]; + builder.build(test[i], random); + + sortingHelper.sort(test[i]); + checkNegativeZero(test[i]); + } + out.println(); + } + + private void testFloatingPointSorting(int length, TestRandom random) { + if (length < 6) { + return; + } + final int MAX = 14; + int s = 4; + + for (int a = 0; a < MAX; ++a) { + for (int g = 0; g < MAX; ++g) { + for (int z = 0; z < MAX; ++z) { + for (int n = 0; n < MAX; ++n) { + for (int p = 0; p < MAX; ++p) { + if (a + g + z + n + p + s != length) { + continue; + } + for (int i = 5; i < test.length; ++i) { + printTestName("Test float-pointing sorting", random, length, + ", a = " + a + ", g = " + g + ", z = " + z + + ", n = " + n + ", p = " + p + ", " + getType(i)); + FloatingPointBuilder builder = FloatingPointBuilder.values()[i - 5]; + builder.build(gold[i], a, g, z, n, p, random); + copy(test[i], gold[i]); + scramble(test[i], random); + sortingHelper.sort(test[i]); + compare(test[i], gold[i], a, n + 2, g); + } + } + } + } + } + } + for (int m = MAX; m > 4; --m) { + int g = length / m; + int a = length - g - g - g - g - s; + + for (int i = 5; i < test.length; ++i) { + printTestName("Test float-pointing sorting", random, length, + ", a = " + a + ", g = " + g + ", z = " + g + + ", n = " + g + ", p = " + g + ", " + getType(i)); + FloatingPointBuilder builder = FloatingPointBuilder.values()[i - 5]; + builder.build(gold[i], a, g, g, g, g, random); + copy(test[i], gold[i]); + scramble(test[i], random); + sortingHelper.sort(test[i]); + compare(test[i], gold[i], a, g + 2, g); + } + } + out.println(); + } + + private void prepareSubArray(int[] a, int fromIndex, int toIndex) { + for (int i = 0; i < fromIndex; ++i) { + a[i] = A380; + } + int middle = (fromIndex + toIndex) >>> 1; + int k = 0; + + for (int i = fromIndex; i < middle; ++i) { + a[i] = k++; + } + + for (int i = middle; i < toIndex; ++i) { + a[i] = k--; + } + + for (int i = toIndex; i < a.length; ++i) { + a[i] = B747; + } + } + + private void scramble(Object a, Random random) { + if (a instanceof int[]) { + scramble((int[]) a, random); + } else if (a instanceof long[]) { + scramble((long[]) a, random); + } else if (a instanceof byte[]) { + scramble((byte[]) a, random); + } else if (a instanceof char[]) { + scramble((char[]) a, random); + } else if (a instanceof short[]) { + scramble((short[]) a, random); + } else if (a instanceof float[]) { + scramble((float[]) a, random); + } else if (a instanceof double[]) { + scramble((double[]) a, random); + } else { + fail(a); + } + } + + private void scramble(int[] a, Random random) { + for (int i = 0; i < a.length * 7; ++i) { + swap(a, random.nextInt(a.length), random.nextInt(a.length)); + } + } + + private void scramble(long[] a, Random random) { + for (int i = 0; i < a.length * 7; ++i) { + swap(a, random.nextInt(a.length), random.nextInt(a.length)); + } + } + + private void scramble(byte[] a, Random random) { + for (int i = 0; i < a.length * 7; ++i) { + swap(a, random.nextInt(a.length), random.nextInt(a.length)); + } + } + + private void scramble(char[] a, Random random) { + for (int i = 0; i < a.length * 7; ++i) { + swap(a, random.nextInt(a.length), random.nextInt(a.length)); + } + } + + private void scramble(short[] a, Random random) { + for (int i = 0; i < a.length * 7; ++i) { + swap(a, random.nextInt(a.length), random.nextInt(a.length)); + } + } + + private void scramble(float[] a, Random random) { + for (int i = 0; i < a.length * 7; ++i) { + swap(a, random.nextInt(a.length), random.nextInt(a.length)); + } + } + + private void scramble(double[] a, Random random) { + for (int i = 0; i < a.length * 7; ++i) { + swap(a, random.nextInt(a.length), random.nextInt(a.length)); + } + } + + private void swap(int[] a, int i, int j) { + int t = a[i]; a[i] = a[j]; a[j] = t; + } + + private void swap(long[] a, int i, int j) { + long t = a[i]; a[i] = a[j]; a[j] = t; + } + + private void swap(byte[] a, int i, int j) { + byte t = a[i]; a[i] = a[j]; a[j] = t; + } + + private void swap(char[] a, int i, int j) { + char t = a[i]; a[i] = a[j]; a[j] = t; + } + + private void swap(short[] a, int i, int j) { + short t = a[i]; a[i] = a[j]; a[j] = t; + } + + private void swap(float[] a, int i, int j) { + float t = a[i]; a[i] = a[j]; a[j] = t; + } + + private void swap(double[] a, int i, int j) { + double t = a[i]; a[i] = a[j]; a[j] = t; + } + + private void checkWithCheckSum(Object test, Object gold) { + checkSorted(test); + checkCheckSum(test, gold); + } + + private void fail(Object object) { + fail("Unknown type of array: " + object.getClass().getName()); + } + + private void fail(String message) { + err.format("\n*** TEST FAILED ***\n\n%s\n\n", message); + throw new RuntimeException("Test failed"); + } + + private void checkNegativeZero(Object a) { + if (a instanceof float[]) { + checkNegativeZero((float[]) a); + } else if (a instanceof double[]) { + checkNegativeZero((double[]) a); + } else { + fail(a); + } + } + + private void checkNegativeZero(float[] a) { + for (int i = 0; i < a.length - 1; ++i) { + if (Float.floatToRawIntBits(a[i]) == 0 && Float.floatToRawIntBits(a[i + 1]) < 0) { + fail(a[i] + " before " + a[i + 1] + " at position " + i); + } + } + } + + private void checkNegativeZero(double[] a) { + for (int i = 0; i < a.length - 1; ++i) { + if (Double.doubleToRawLongBits(a[i]) == 0 && Double.doubleToRawLongBits(a[i + 1]) < 0) { + fail(a[i] + " before " + a[i + 1] + " at position " + i); + } + } + } + + private void compare(Object a, Object b, int numNaN, int numNeg, int numNegZero) { + if (a instanceof float[]) { + compare((float[]) a, (float[]) b, numNaN, numNeg, numNegZero); + } else if (a instanceof double[]) { + compare((double[]) a, (double[]) b, numNaN, numNeg, numNegZero); + } else { + fail(a); + } + } + + private void compare(float[] a, float[] b, int numNaN, int numNeg, int numNegZero) { + for (int i = a.length - numNaN; i < a.length; ++i) { + if (a[i] == a[i]) { + fail("There must be NaN instead of " + a[i] + " at position " + i); + } + } + final int NEGATIVE_ZERO = Float.floatToIntBits(-0.0f); + + for (int i = numNeg; i < numNeg + numNegZero; ++i) { + if (NEGATIVE_ZERO != Float.floatToIntBits(a[i])) { + fail("There must be -0.0 instead of " + a[i] + " at position " + i); + } + } + + for (int i = 0; i < a.length - numNaN; ++i) { + if (a[i] != b[i]) { + fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); + } + } + } + + private void compare(double[] a, double[] b, int numNaN, int numNeg, int numNegZero) { + for (int i = a.length - numNaN; i < a.length; ++i) { + if (a[i] == a[i]) { + fail("There must be NaN instead of " + a[i] + " at position " + i); + } + } + final long NEGATIVE_ZERO = Double.doubleToLongBits(-0.0d); + + for (int i = numNeg; i < numNeg + numNegZero; ++i) { + if (NEGATIVE_ZERO != Double.doubleToLongBits(a[i])) { + fail("There must be -0.0 instead of " + a[i] + " at position " + i); + } + } + + for (int i = 0; i < a.length - numNaN; ++i) { + if (a[i] != b[i]) { + fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); + } + } + } + + private void compare(Object a, Object b) { + if (a instanceof int[]) { + compare((int[]) a, (int[]) b); + } else if (a instanceof long[]) { + compare((long[]) a, (long[]) b); + } else if (a instanceof byte[]) { + compare((byte[]) a, (byte[]) b); + } else if (a instanceof char[]) { + compare((char[]) a, (char[]) b); + } else if (a instanceof short[]) { + compare((short[]) a, (short[]) b); + } else if (a instanceof float[]) { + compare((float[]) a, (float[]) b); + } else if (a instanceof double[]) { + compare((double[]) a, (double[]) b); + } else { + fail(a); + } + } + + private void compare(int[] a, int[] b) { + for (int i = 0; i < a.length; ++i) { + if (a[i] != b[i]) { + fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); + } + } + } + + private void compare(long[] a, long[] b) { + for (int i = 0; i < a.length; ++i) { + if (a[i] != b[i]) { + fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); + } + } + } + + private void compare(byte[] a, byte[] b) { + for (int i = 0; i < a.length; ++i) { + if (a[i] != b[i]) { + fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); + } + } + } + + private void compare(char[] a, char[] b) { + for (int i = 0; i < a.length; ++i) { + if (a[i] != b[i]) { + fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); + } + } + } + + private void compare(short[] a, short[] b) { + for (int i = 0; i < a.length; ++i) { + if (a[i] != b[i]) { + fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); + } + } + } + + private void compare(float[] a, float[] b) { + for (int i = 0; i < a.length; ++i) { + if (a[i] != b[i]) { + fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); + } + } + } + + private void compare(double[] a, double[] b) { + for (int i = 0; i < a.length; ++i) { + if (a[i] != b[i]) { + fail("There must be " + b[i] + " instead of " + a[i] + " at position " + i); + } + } + } + + private String getType(int i) { + Object a = test[i]; + + if (a instanceof int[]) { + return "INT "; + } + if (a instanceof long[]) { + return "LONG "; + } + if (a instanceof byte[]) { + return "BYTE "; + } + if (a instanceof char[]) { + return "CHAR "; + } + if (a instanceof short[]) { + return "SHORT "; + } + if (a instanceof float[]) { + return "FLOAT "; + } + if (a instanceof double[]) { + return "DOUBLE"; + } + fail(a); + return null; + } + + private void checkSorted(Object a) { + if (a instanceof int[]) { + checkSorted((int[]) a); + } else if (a instanceof long[]) { + checkSorted((long[]) a); + } else if (a instanceof byte[]) { + checkSorted((byte[]) a); + } else if (a instanceof char[]) { + checkSorted((char[]) a); + } else if (a instanceof short[]) { + checkSorted((short[]) a); + } else if (a instanceof float[]) { + checkSorted((float[]) a); + } else if (a instanceof double[]) { + checkSorted((double[]) a); + } else { + fail(a); + } + } + + private void checkSorted(int[] a) { + for (int i = 0; i < a.length - 1; ++i) { + if (a[i] > a[i + 1]) { + fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); + } + } + } + + private void checkSorted(long[] a) { + for (int i = 0; i < a.length - 1; ++i) { + if (a[i] > a[i + 1]) { + fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); + } + } + } + + private void checkSorted(byte[] a) { + for (int i = 0; i < a.length - 1; ++i) { + if (a[i] > a[i + 1]) { + fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); + } + } + } + + private void checkSorted(char[] a) { + for (int i = 0; i < a.length - 1; ++i) { + if (a[i] > a[i + 1]) { + fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); + } + } + } + + private void checkSorted(short[] a) { + for (int i = 0; i < a.length - 1; ++i) { + if (a[i] > a[i + 1]) { + fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); + } + } + } + + private void checkSorted(float[] a) { + for (int i = 0; i < a.length - 1; ++i) { + if (a[i] > a[i + 1]) { + fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); + } + } + } + + private void checkSorted(double[] a) { + for (int i = 0; i < a.length - 1; ++i) { + if (a[i] > a[i + 1]) { + fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); + } + } + } + + private void checkCheckSum(Object test, Object gold) { + if (checkSumXor(test) != checkSumXor(gold)) { + fail("Original and sorted arrays are not identical [^]"); + } + if (checkSumPlus(test) != checkSumPlus(gold)) { + fail("Original and sorted arrays are not identical [+]"); + } + } + + private int checkSumXor(Object a) { + if (a instanceof int[]) { + return checkSumXor((int[]) a); + } + if (a instanceof long[]) { + return checkSumXor((long[]) a); + } + if (a instanceof byte[]) { + return checkSumXor((byte[]) a); + } + if (a instanceof char[]) { + return checkSumXor((char[]) a); + } + if (a instanceof short[]) { + return checkSumXor((short[]) a); + } + if (a instanceof float[]) { + return checkSumXor((float[]) a); + } + if (a instanceof double[]) { + return checkSumXor((double[]) a); + } + fail(a); + return -1; + } + + private int checkSumXor(int[] a) { + int checkSum = 0; + + for (int e : a) { + checkSum ^= e; + } + return checkSum; + } + + private int checkSumXor(long[] a) { + long checkSum = 0; + + for (long e : a) { + checkSum ^= e; + } + return (int) checkSum; + } + + private int checkSumXor(byte[] a) { + byte checkSum = 0; + + for (byte e : a) { + checkSum ^= e; + } + return checkSum; + } + + private int checkSumXor(char[] a) { + char checkSum = 0; + + for (char e : a) { + checkSum ^= e; + } + return checkSum; + } + + private int checkSumXor(short[] a) { + short checkSum = 0; + + for (short e : a) { + checkSum ^= e; + } + return checkSum; + } + + private int checkSumXor(float[] a) { + int checkSum = 0; + + for (float e : a) { + checkSum ^= (int) e; + } + return checkSum; + } + + private int checkSumXor(double[] a) { + int checkSum = 0; + + for (double e : a) { + checkSum ^= (int) e; + } + return checkSum; + } + + private int checkSumPlus(Object a) { + if (a instanceof int[]) { + return checkSumPlus((int[]) a); + } + if (a instanceof long[]) { + return checkSumPlus((long[]) a); + } + if (a instanceof byte[]) { + return checkSumPlus((byte[]) a); + } + if (a instanceof char[]) { + return checkSumPlus((char[]) a); + } + if (a instanceof short[]) { + return checkSumPlus((short[]) a); + } + if (a instanceof float[]) { + return checkSumPlus((float[]) a); + } + if (a instanceof double[]) { + return checkSumPlus((double[]) a); + } + fail(a); + return -1; + } + + private int checkSumPlus(int[] a) { + int checkSum = 0; + + for (int e : a) { + checkSum += e; + } + return checkSum; + } + + private int checkSumPlus(long[] a) { + long checkSum = 0; + + for (long e : a) { + checkSum += e; + } + return (int) checkSum; + } + + private int checkSumPlus(byte[] a) { + byte checkSum = 0; + + for (byte e : a) { + checkSum += e; + } + return checkSum; + } + + private int checkSumPlus(char[] a) { + char checkSum = 0; + + for (char e : a) { + checkSum += e; + } + return checkSum; + } + + private int checkSumPlus(short[] a) { + short checkSum = 0; + + for (short e : a) { + checkSum += e; + } + return checkSum; + } + + private int checkSumPlus(float[] a) { + int checkSum = 0; + + for (float e : a) { + checkSum += (int) e; + } + return checkSum; + } + + private int checkSumPlus(double[] a) { + int checkSum = 0; + + for (double e : a) { + checkSum += (int) e; + } + return checkSum; + } + + private void sortByInsertionSort(Object a) { + SortingHelper.INSERTION_SORT.sort(a); + } + + private void checkSubArray(Object a, int fromIndex, int toIndex) { + if (a instanceof int[]) { + checkSubArray((int[]) a, fromIndex, toIndex); + } else if (a instanceof long[]) { + checkSubArray((long[]) a, fromIndex, toIndex); + } else if (a instanceof byte[]) { + checkSubArray((byte[]) a, fromIndex, toIndex); + } else if (a instanceof char[]) { + checkSubArray((char[]) a, fromIndex, toIndex); + } else if (a instanceof short[]) { + checkSubArray((short[]) a, fromIndex, toIndex); + } else if (a instanceof float[]) { + checkSubArray((float[]) a, fromIndex, toIndex); + } else if (a instanceof double[]) { + checkSubArray((double[]) a, fromIndex, toIndex); + } else { + fail(a); + } + } + + private void checkSubArray(int[] a, int fromIndex, int toIndex) { + for (int i = 0; i < fromIndex; ++i) { + if (a[i] != A380) { + fail("Range sort changes left element at position " + i + hex(a[i], A380)); + } + } + + for (int i = fromIndex; i < toIndex - 1; ++i) { + if (a[i] > a[i + 1]) { + fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); + } + } + + for (int i = toIndex; i < a.length; ++i) { + if (a[i] != B747) { + fail("Range sort changes right element at position " + i + hex(a[i], B747)); + } + } + } + + private void checkSubArray(long[] a, int fromIndex, int toIndex) { + for (int i = 0; i < fromIndex; ++i) { + if (a[i] != (long) A380) { + fail("Range sort changes left element at position " + i + hex(a[i], A380)); + } + } + + for (int i = fromIndex; i < toIndex - 1; ++i) { + if (a[i] > a[i + 1]) { + fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); + } + } + + for (int i = toIndex; i < a.length; ++i) { + if (a[i] != (long) B747) { + fail("Range sort changes right element at position " + i + hex(a[i], B747)); + } + } + } + + private void checkSubArray(byte[] a, int fromIndex, int toIndex) { + for (int i = 0; i < fromIndex; ++i) { + if (a[i] != (byte) A380) { + fail("Range sort changes left element at position " + i + hex(a[i], A380)); + } + } + + for (int i = fromIndex; i < toIndex - 1; ++i) { + if (a[i] > a[i + 1]) { + fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); + } + } + + for (int i = toIndex; i < a.length; ++i) { + if (a[i] != (byte) B747) { + fail("Range sort changes right element at position " + i + hex(a[i], B747)); + } + } + } + + private void checkSubArray(char[] a, int fromIndex, int toIndex) { + for (int i = 0; i < fromIndex; ++i) { + if (a[i] != (char) A380) { + fail("Range sort changes left element at position " + i + hex(a[i], A380)); + } + } + + for (int i = fromIndex; i < toIndex - 1; ++i) { + if (a[i] > a[i + 1]) { + fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); + } + } + + for (int i = toIndex; i < a.length; ++i) { + if (a[i] != (char) B747) { + fail("Range sort changes right element at position " + i + hex(a[i], B747)); + } + } + } + + private void checkSubArray(short[] a, int fromIndex, int toIndex) { + for (int i = 0; i < fromIndex; ++i) { + if (a[i] != (short) A380) { + fail("Range sort changes left element at position " + i + hex(a[i], A380)); + } + } + + for (int i = fromIndex; i < toIndex - 1; ++i) { + if (a[i] > a[i + 1]) { + fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); + } + } + + for (int i = toIndex; i < a.length; ++i) { + if (a[i] != (short) B747) { + fail("Range sort changes right element at position " + i + hex(a[i], B747)); + } + } + } + + private void checkSubArray(float[] a, int fromIndex, int toIndex) { + for (int i = 0; i < fromIndex; ++i) { + if (a[i] != (float) A380) { + fail("Range sort changes left element at position " + i + hex((long) a[i], A380)); + } + } + + for (int i = fromIndex; i < toIndex - 1; ++i) { + if (a[i] > a[i + 1]) { + fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); + } + } + + for (int i = toIndex; i < a.length; ++i) { + if (a[i] != (float) B747) { + fail("Range sort changes right element at position " + i + hex((long) a[i], B747)); + } + } + } + + private void checkSubArray(double[] a, int fromIndex, int toIndex) { + for (int i = 0; i < fromIndex; ++i) { + if (a[i] != (double) A380) { + fail("Range sort changes left element at position " + i + hex((long) a[i], A380)); + } + } + + for (int i = fromIndex; i < toIndex - 1; ++i) { + if (a[i] > a[i + 1]) { + fail("Array is not sorted at " + i + "-th position: " + a[i] + " and " + a[i + 1]); + } + } + + for (int i = toIndex; i < a.length; ++i) { + if (a[i] != (double) B747) { + fail("Range sort changes right element at position " + i + hex((long) a[i], B747)); + } + } + } + + private void checkRange(Object a, int m) { + if (a instanceof int[]) { + checkRange((int[]) a, m); + } else if (a instanceof long[]) { + checkRange((long[]) a, m); + } else if (a instanceof byte[]) { + checkRange((byte[]) a, m); + } else if (a instanceof char[]) { + checkRange((char[]) a, m); + } else if (a instanceof short[]) { + checkRange((short[]) a, m); + } else if (a instanceof float[]) { + checkRange((float[]) a, m); + } else if (a instanceof double[]) { + checkRange((double[]) a, m); + } else { + fail(a); + } + } + + private void checkRange(int[] a, int m) { + try { + sortingHelper.sort(a, m + 1, m); + fail(sortingHelper + " does not throw IllegalArgumentException " + + "as expected: fromIndex = " + (m + 1) + ", toIndex = " + m); + } catch (IllegalArgumentException iae) { + try { + sortingHelper.sort(a, -m, a.length); + fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + + "as expected: fromIndex = " + (-m)); + } catch (ArrayIndexOutOfBoundsException aoe) { + try { + sortingHelper.sort(a, 0, a.length + m); + fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + + "as expected: toIndex = " + (a.length + m)); + } catch (ArrayIndexOutOfBoundsException expected) {} + } + } + } + + private void checkRange(long[] a, int m) { + try { + sortingHelper.sort(a, m + 1, m); + fail(sortingHelper + " does not throw IllegalArgumentException " + + "as expected: fromIndex = " + (m + 1) + ", toIndex = " + m); + } catch (IllegalArgumentException iae) { + try { + sortingHelper.sort(a, -m, a.length); + fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + + "as expected: fromIndex = " + (-m)); + } catch (ArrayIndexOutOfBoundsException aoe) { + try { + sortingHelper.sort(a, 0, a.length + m); + fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + + "as expected: toIndex = " + (a.length + m)); + } catch (ArrayIndexOutOfBoundsException expected) {} + } + } + } + + private void checkRange(byte[] a, int m) { + try { + sortingHelper.sort(a, m + 1, m); + fail(sortingHelper + " does not throw IllegalArgumentException " + + "as expected: fromIndex = " + (m + 1) + ", toIndex = " + m); + } catch (IllegalArgumentException iae) { + try { + sortingHelper.sort(a, -m, a.length); + fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + + "as expected: fromIndex = " + (-m)); + } catch (ArrayIndexOutOfBoundsException aoe) { + try { + sortingHelper.sort(a, 0, a.length + m); + fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + + "as expected: toIndex = " + (a.length + m)); + } catch (ArrayIndexOutOfBoundsException expected) {} + } + } + } + + private void checkRange(char[] a, int m) { + try { + sortingHelper.sort(a, m + 1, m); + fail(sortingHelper + " does not throw IllegalArgumentException " + + "as expected: fromIndex = " + (m + 1) + ", toIndex = " + m); + } catch (IllegalArgumentException iae) { + try { + sortingHelper.sort(a, -m, a.length); + fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + + "as expected: fromIndex = " + (-m)); + } catch (ArrayIndexOutOfBoundsException aoe) { + try { + sortingHelper.sort(a, 0, a.length + m); + fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + + "as expected: toIndex = " + (a.length + m)); + } catch (ArrayIndexOutOfBoundsException expected) {} + } + } + } + + private void checkRange(short[] a, int m) { + try { + sortingHelper.sort(a, m + 1, m); + fail(sortingHelper + " does not throw IllegalArgumentException " + + "as expected: fromIndex = " + (m + 1) + ", toIndex = " + m); + } catch (IllegalArgumentException iae) { + try { + sortingHelper.sort(a, -m, a.length); + fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + + "as expected: fromIndex = " + (-m)); + } catch (ArrayIndexOutOfBoundsException aoe) { + try { + sortingHelper.sort(a, 0, a.length + m); + fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + + "as expected: toIndex = " + (a.length + m)); + } catch (ArrayIndexOutOfBoundsException expected) {} + } + } + } + + private void checkRange(float[] a, int m) { + try { + sortingHelper.sort(a, m + 1, m); + fail(sortingHelper + " does not throw IllegalArgumentException " + + "as expected: fromIndex = " + (m + 1) + ", toIndex = " + m); + } catch (IllegalArgumentException iae) { + try { + sortingHelper.sort(a, -m, a.length); + fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + + "as expected: fromIndex = " + (-m)); + } catch (ArrayIndexOutOfBoundsException aoe) { + try { + sortingHelper.sort(a, 0, a.length + m); + fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + + "as expected: toIndex = " + (a.length + m)); + } catch (ArrayIndexOutOfBoundsException expected) {} + } + } + } + + private void checkRange(double[] a, int m) { + try { + sortingHelper.sort(a, m + 1, m); + fail(sortingHelper + " does not throw IllegalArgumentException " + + "as expected: fromIndex = " + (m + 1) + ", toIndex = " + m); + } catch (IllegalArgumentException iae) { + try { + sortingHelper.sort(a, -m, a.length); + fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + + "as expected: fromIndex = " + (-m)); + } catch (ArrayIndexOutOfBoundsException aoe) { + try { + sortingHelper.sort(a, 0, a.length + m); + fail(sortingHelper + " does not throw ArrayIndexOutOfBoundsException " + + "as expected: toIndex = " + (a.length + m)); + } catch (ArrayIndexOutOfBoundsException expected) {} + } + } + } + + private void copy(Object dst, Object src) { + if (src instanceof float[]) { + copy((float[]) dst, (float[]) src); + } else if (src instanceof double[]) { + copy((double[]) dst, (double[]) src); + } else { + fail(src); + } + } + + private void copy(float[] dst, float[] src) { + System.arraycopy(src, 0, dst, 0, src.length); + } + + private void copy(double[] dst, double[] src) { + System.arraycopy(src, 0, dst, 0, src.length); + } + + private void createData(int length) { + gold = new Object[] { + new int[length], new long[length], + new byte[length], new char[length], new short[length], + new float[length], new double[length] + }; + + test = new Object[] { + new int[length], new long[length], + new byte[length], new char[length], new short[length], + new float[length], new double[length] + }; + } + + private void convertData(int length) { + for (int i = 0; i < gold.length; ++i) { + TypeConverter converter = TypeConverter.values()[i]; + converter.convert((int[]) gold[0], gold[i], fix); + } + + for (int i = 0; i < gold.length; ++i) { + System.arraycopy(gold[i], 0, test[i], 0, length); + } + } + + private String hex(long a, int b) { + return ": " + Long.toHexString(a) + ", must be " + Integer.toHexString(b); + } + + private void printTestName(String test, int length, String message) { + out.println("[" + sortingHelper + "] '" + test + "' length = " + length + message); + } + + private void printTestName(String test, TestRandom random, int length, String message) { + out.println("[" + sortingHelper + "] '" + test + + "' length = " + length + ", random = " + random + message); + } + + private enum TypeConverter { + + INT { + @Override + void convert(int[] src, Object dst, boolean fix) { + if (fix) { + src[0] = Integer.MIN_VALUE; + } + } + }, + + LONG { + @Override + void convert(int[] src, Object dst, boolean fix) { + long[] b = (long[]) dst; + + for (int i = 0; i < src.length; ++i) { + b[i] = src[i]; + } + if (fix) { + b[0] = Long.MIN_VALUE; + } + } + }, + + BYTE { + @Override + void convert(int[] src, Object dst, boolean fix) { + byte[] b = (byte[]) dst; + + for (int i = 0; i < src.length; ++i) { + b[i] = (byte) src[i]; + } + if (fix) { + b[0] = Byte.MIN_VALUE; + } + } + }, + + CHAR { + @Override + void convert(int[] src, Object dst, boolean fix) { + char[] b = (char[]) dst; + + for (int i = 0; i < src.length; ++i) { + b[i] = (char) src[i]; + } + if (fix) { + b[0] = Character.MIN_VALUE; + } + } + }, + + SHORT { + @Override + void convert(int[] src, Object dst, boolean fix) { + short[] b = (short[]) dst; + + for (int i = 0; i < src.length; ++i) { + b[i] = (short) src[i]; + } + if (fix) { + b[0] = Short.MIN_VALUE; + } + } + }, + + FLOAT { + @Override + void convert(int[] src, Object dst, boolean fix) { + float[] b = (float[]) dst; + + for (int i = 0; i < src.length; ++i) { + b[i] = (float) src[i]; + } + if (fix) { + b[0] = Float.NEGATIVE_INFINITY; + } + } + }, + + DOUBLE { + @Override + void convert(int[] src, Object dst, boolean fix) { + double[] b = (double[]) dst; + + for (int i = 0; i < src.length; ++i) { + b[i] = src[i]; + } + if (fix) { + b[0] = Double.NEGATIVE_INFINITY; + } + } + }; + + abstract void convert(int[] src, Object dst, boolean fix); + } + + private enum SortedBuilder { + + STEPS { + @Override + void build(int[] a, int m) { + for (int i = 0; i < m; ++i) { + a[i] = 0; + } + + for (int i = m; i < a.length; ++i) { + a[i] = 1; + } + } + }; + + abstract void build(int[] a, int m); + } + + private enum UnsortedBuilder { + + RANDOM { + @Override + void build(int[] a, int m, Random random) { + for (int i = 0; i < a.length; ++i) { + a[i] = random.nextInt(); + } + } + }, + + PERMUTATION { + @Override + void build(int[] a, int m, Random random) { + int mask = ~(0x000000FF << (random.nextInt(4) * 2)); + + for (int i = 0; i < a.length; ++i) { + a[i] = i & mask; + } + for (int i = a.length; i > 1; --i) { + int k = random.nextInt(i); + int t = a[i - 1]; a[i - 1] = a[k]; a[k] = t; + } + } + }, + + UNIFORM { + @Override + void build(int[] a, int m, Random random) { + int mask = (m << 15) - 1; + + for (int i = 0; i < a.length; ++i) { + a[i] = random.nextInt() & mask; + } + } + }, + + REPEATED { + @Override + void build(int[] a, int m, Random random) { + for (int i = 0; i < a.length; ++i) { + a[i] = i % m; + } + } + }, + + DUPLICATED { + @Override + void build(int[] a, int m, Random random) { + for (int i = 0; i < a.length; ++i) { + a[i] = random.nextInt(m); + } + } + }, + + SAWTOOTH { + @Override + void build(int[] a, int m, Random random) { + int incCount = 1; + int decCount = a.length; + int i = 0; + int period = m--; + + while (true) { + for (int k = 1; k <= period; ++k) { + if (i >= a.length) { + return; + } + a[i++] = incCount++; + } + period += m; + + for (int k = 1; k <= period; ++k) { + if (i >= a.length) { + return; + } + a[i++] = decCount--; + } + period += m; + } + } + }, + + SHUFFLE { + @Override + void build(int[] a, int m, Random random) { + for (int i = 0, j = 0, k = 1; i < a.length; ++i) { + a[i] = random.nextInt(m) > 0 ? (j += 2) : (k += 2); + } + } + }; + + abstract void build(int[] a, int m, Random random); + } + + private enum StructuredBuilder { + + ASCENDING { + @Override + void build(int[] a, int m) { + for (int i = 0; i < a.length; ++i) { + a[i] = m + i; + } + } + }, + + DESCENDING { + @Override + void build(int[] a, int m) { + for (int i = 0; i < a.length; ++i) { + a[i] = a.length - m - i; + } + } + }, + + EQUAL { + @Override + void build(int[] a, int m) { + Arrays.fill(a, m); + } + }, + + MASKED { + @Override + void build(int[] a, int m) { + int mask = (m << 15) - 1; + + for (int i = 0; i < a.length; ++i) { + a[i] = (i ^ 0xFF) & mask; + } + } + }, + + ORGAN_PIPES { + @Override + void build(int[] a, int m) { + int middle = a.length / (m + 1); + + for (int i = 0; i < middle; ++i) { + a[i] = i; + } + + for (int i = middle; i < a.length; ++i) { + a[i] = a.length - i - 1; + } + } + }, + + STAGGER { + @Override + void build(int[] a, int m) { + for (int i = 0; i < a.length; ++i) { + a[i] = (i * m + i) % a.length; + } + } + }, + + PLATEAU { + @Override + void build(int[] a, int m) { + for (int i = 0; i < a.length; ++i) { + a[i] = Math.min(i, m); + } + } + }, + + LATCH { + @Override + void build(int[] a, int m) { + int max = a.length / m; + max = Math.max(max, 2); + + for (int i = 0; i < a.length; ++i) { + a[i] = i % max; + } + } + }, + + POINT { + @Override + void build(int[] a, int m) { + Arrays.fill(a, 0); + a[a.length / 2] = m; + } + }, + + LINE { + @Override + void build(int[] a, int m) { + for (int i = 0; i < a.length; ++i) { + a[i] = i; + } + reverse(a, m, a.length - 1); + } + }, + + PEARL { + @Override + void build(int[] a, int m) { + for (int i = 0; i < a.length; ++i) { + a[i] = i; + } + reverse(a, 0, Math.min(m, a.length)); + } + }, + + RING { + @Override + void build(int[] a, int m) { + int k1 = a.length / 3; + int k2 = a.length / 3 * 2; + int level = a.length / 3; + + for (int i = 0, k = level; i < k1; ++i) { + a[i] = k--; + } + + for (int i = k1; i < k2; ++i) { + a[i] = 0; + } + + for (int i = k2, k = level; i < a.length; ++i) { + a[i] = k--; + } + } + }; + + abstract void build(int[] a, int m); + + private static void reverse(int[] a, int lo, int hi) { + for (--hi; lo < hi; ) { + int tmp = a[lo]; + a[lo++] = a[hi]; + a[hi--] = tmp; + } + } + } + + private enum NegativeZeroBuilder { + + FLOAT { + @Override + void build(Object o, Random random) { + float[] a = (float[]) o; + + for (int i = 0; i < a.length; ++i) { + a[i] = random.nextBoolean() ? -0.0f : 0.0f; + } + } + }, + + DOUBLE { + @Override + void build(Object o, Random random) { + double[] a = (double[]) o; + + for (int i = 0; i < a.length; ++i) { + a[i] = random.nextBoolean() ? -0.0d : 0.0d; + } + } + }; + + abstract void build(Object o, Random random); + } + + private enum FloatingPointBuilder { + + FLOAT { + @Override + void build(Object o, int a, int g, int z, int n, int p, Random random) { + float negativeValue = -random.nextFloat(); + float positiveValue = random.nextFloat(); + float[] data = (float[]) o; + int fromIndex = 0; + + fillWithValue(data, Float.NEGATIVE_INFINITY, fromIndex, 1); + fromIndex += 1; + + fillWithValue(data, -Float.MAX_VALUE, fromIndex, 1); + fromIndex += 1; + + fillWithValue(data, negativeValue, fromIndex, n); + fromIndex += n; + + fillWithValue(data, -0.0f, fromIndex, g); + fromIndex += g; + + fillWithValue(data, 0.0f, fromIndex, z); + fromIndex += z; + + fillWithValue(data, positiveValue, fromIndex, p); + fromIndex += p; + + fillWithValue(data, Float.MAX_VALUE, fromIndex, 1); + fromIndex += 1; + + fillWithValue(data, Float.POSITIVE_INFINITY, fromIndex, 1); + fromIndex += 1; + + fillWithValue(data, Float.NaN, fromIndex, a); + } + }, + + DOUBLE { + @Override + void build(Object o, int a, int g, int z, int n, int p, Random random) { + double negativeValue = -random.nextFloat(); + double positiveValue = random.nextFloat(); + double[] data = (double[]) o; + int fromIndex = 0; + + fillWithValue(data, Double.NEGATIVE_INFINITY, fromIndex, 1); + fromIndex++; + + fillWithValue(data, -Double.MAX_VALUE, fromIndex, 1); + fromIndex++; + + fillWithValue(data, negativeValue, fromIndex, n); + fromIndex += n; + + fillWithValue(data, -0.0d, fromIndex, g); + fromIndex += g; + + fillWithValue(data, 0.0d, fromIndex, z); + fromIndex += z; + + fillWithValue(data, positiveValue, fromIndex, p); + fromIndex += p; + + fillWithValue(data, Double.MAX_VALUE, fromIndex, 1); + fromIndex += 1; + + fillWithValue(data, Double.POSITIVE_INFINITY, fromIndex, 1); + fromIndex += 1; + + fillWithValue(data, Double.NaN, fromIndex, a); + } + }; + + abstract void build(Object o, int a, int g, int z, int n, int p, Random random); + + private static void fillWithValue(float[] a, float value, int fromIndex, int count) { + for (int i = fromIndex; i < fromIndex + count; ++i) { + a[i] = value; + } + } + + private static void fillWithValue(double[] a, double value, int fromIndex, int count) { + for (int i = fromIndex; i < fromIndex + count; ++i) { + a[i] = value; + } + } + } + + private static class TestRandom extends Random { + + private static final TestRandom DEDA = new TestRandom(0xDEDA); + private static final TestRandom BABA = new TestRandom(0xBABA); + private static final TestRandom C0FFEE = new TestRandom(0xC0FFEE); + + private TestRandom(long seed) { + super(seed); + this.seed = Long.toHexString(seed).toUpperCase(); + } + + @Override + public String toString() { + return seed; + } + + private final String seed; + } +} diff --git a/test/jdk/java/util/Arrays/java.base/java/util/SortingHelper.java b/test/jdk/java/util/Arrays/java.base/java/util/SortingHelper.java index 3357aa959ee64..dd2c3e153527d 100644 --- a/test/jdk/java/util/Arrays/java.base/java/util/SortingHelper.java +++ b/test/jdk/java/util/Arrays/java.base/java/util/SortingHelper.java @@ -1,352 +1,331 @@ -/* - * Copyright (c) 2019, Oracle and/or its affiliates. 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. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.util; - -/** - * This class provides access to package-private - * methods of DualPivotQuicksort class. - * - * @author Vladimir Yaroslavskiy - * - * @version 2019.09.19 - * - * @since 14 - */ -public enum SortingHelper { - - DUAL_PIVOT_QUICKSORT("Dual-Pivot Quicksort") { - - @Override - public void sort(Object a) { - if (a instanceof int[]) { - DualPivotQuicksort.sort((int[]) a, SEQUENTIAL, 0, ((int[]) a).length); - } else if (a instanceof long[]) { - DualPivotQuicksort.sort((long[]) a, SEQUENTIAL, 0, ((long[]) a).length); - } else if (a instanceof byte[]) { - DualPivotQuicksort.sort((byte[]) a, 0, ((byte[]) a).length); - } else if (a instanceof char[]) { - DualPivotQuicksort.sort((char[]) a, SEQUENTIAL, 0, ((char[]) a).length); - } else if (a instanceof short[]) { - DualPivotQuicksort.sort((short[]) a, SEQUENTIAL, 0, ((short[]) a).length); - } else if (a instanceof float[]) { - DualPivotQuicksort.sort((float[]) a, SEQUENTIAL, 0, ((float[]) a).length); - } else if (a instanceof double[]) { - DualPivotQuicksort.sort((double[]) a, SEQUENTIAL, 0, ((double[]) a).length); - } else { - fail(a); - } - } - - @Override - public void sort(Object a, int low, int high) { - if (a instanceof int[]) { - DualPivotQuicksort.sort((int[]) a, SEQUENTIAL, low, high); - } else if (a instanceof long[]) { - DualPivotQuicksort.sort((long[]) a, SEQUENTIAL, low, high); - } else if (a instanceof byte[]) { - DualPivotQuicksort.sort((byte[]) a, low, high); - } else if (a instanceof char[]) { - DualPivotQuicksort.sort((char[]) a, SEQUENTIAL, low, high); - } else if (a instanceof short[]) { - DualPivotQuicksort.sort((short[]) a, SEQUENTIAL, low, high); - } else if (a instanceof float[]) { - DualPivotQuicksort.sort((float[]) a, SEQUENTIAL, low, high); - } else if (a instanceof double[]) { - DualPivotQuicksort.sort((double[]) a, SEQUENTIAL, low, high); - } else { - fail(a); - } - } - - @Override - public void sort(Object[] a) { - fail(a); - } - - @Override - public void sort(Object[] a, Comparator comparator) { - fail(a); - } - }, - - PARALLEL_SORT("Parallel sort") { - - @Override - public void sort(Object a) { - if (a instanceof int[]) { - DualPivotQuicksort.sort((int[]) a, PARALLEL, 0, ((int[]) a).length); - } else if (a instanceof long[]) { - DualPivotQuicksort.sort((long[]) a, PARALLEL, 0, ((long[]) a).length); - } else if (a instanceof byte[]) { - DualPivotQuicksort.sort((byte[]) a, 0, ((byte[]) a).length); - } else if (a instanceof char[]) { - DualPivotQuicksort.sort((char[]) a, PARALLEL, 0, ((char[]) a).length); - } else if (a instanceof short[]) { - DualPivotQuicksort.sort((short[]) a, PARALLEL, 0, ((short[]) a).length); - } else if (a instanceof float[]) { - DualPivotQuicksort.sort((float[]) a, PARALLEL, 0, ((float[]) a).length); - } else if (a instanceof double[]) { - DualPivotQuicksort.sort((double[]) a, PARALLEL, 0, ((double[]) a).length); - } else { - fail(a); - } - } - - @Override - public void sort(Object a, int low, int high) { - if (a instanceof int[]) { - DualPivotQuicksort.sort((int[]) a, PARALLEL, low, high); - } else if (a instanceof long[]) { - DualPivotQuicksort.sort((long[]) a, PARALLEL, low, high); - } else if (a instanceof byte[]) { - DualPivotQuicksort.sort((byte[]) a, low, high); - } else if (a instanceof char[]) { - DualPivotQuicksort.sort((char[]) a, PARALLEL, low, high); - } else if (a instanceof short[]) { - DualPivotQuicksort.sort((short[]) a, PARALLEL, low, high); - } else if (a instanceof float[]) { - DualPivotQuicksort.sort((float[]) a, PARALLEL, low, high); - } else if (a instanceof double[]) { - DualPivotQuicksort.sort((double[]) a, PARALLEL, low, high); - } else { - fail(a); - } - } - - @Override - public void sort(Object[] a) { - fail(a); - } - - @Override - public void sort(Object[] a, Comparator comparator) { - fail(a); - } - }, - - HEAP_SORT("Heap sort") { - - @Override - public void sort(Object a) { - if (a instanceof int[]) { - DualPivotQuicksort.sort(null, (int[]) a, BIG_DEPTH, 0, ((int[]) a).length); - } else if (a instanceof long[]) { - DualPivotQuicksort.sort(null, (long[]) a, BIG_DEPTH, 0, ((long[]) a).length); - } else if (a instanceof byte[]) { - DualPivotQuicksort.sort((byte[]) a, 0, ((byte[]) a).length); - } else if (a instanceof char[]) { - DualPivotQuicksort.sort((char[]) a, BIG_DEPTH, 0, ((char[]) a).length); - } else if (a instanceof short[]) { - DualPivotQuicksort.sort((short[]) a, BIG_DEPTH, 0, ((short[]) a).length); - } else if (a instanceof float[]) { - DualPivotQuicksort.sort(null, (float[]) a, BIG_DEPTH, 0, ((float[]) a).length); - } else if (a instanceof double[]) { - DualPivotQuicksort.sort(null, (double[]) a, BIG_DEPTH, 0, ((double[]) a).length); - } else { - fail(a); - } - } - - @Override - public void sort(Object a, int low, int high) { - if (a instanceof int[]) { - DualPivotQuicksort.sort(null, (int[]) a, BIG_DEPTH, low, high); - } else if (a instanceof long[]) { - DualPivotQuicksort.sort(null, (long[]) a, BIG_DEPTH, low, high); - } else if (a instanceof byte[]) { - DualPivotQuicksort.sort((byte[]) a, low, high); - } else if (a instanceof char[]) { - DualPivotQuicksort.sort((char[]) a, BIG_DEPTH, low, high); - } else if (a instanceof short[]) { - DualPivotQuicksort.sort((short[]) a, BIG_DEPTH, low, high); - } else if (a instanceof float[]) { - DualPivotQuicksort.sort(null, (float[]) a, BIG_DEPTH, low, high); - } else if (a instanceof double[]) { - DualPivotQuicksort.sort(null, (double[]) a, BIG_DEPTH, low, high); - } else { - fail(a); - } - } - - @Override - public void sort(Object[] a) { - fail(a); - } - - @Override - public void sort(Object[] a, Comparator comparator) { - fail(a); - } - }, - - ARRAYS_SORT("Arrays.sort") { - - @Override - public void sort(Object a) { - if (a instanceof int[]) { - Arrays.sort((int[]) a); - } else if (a instanceof long[]) { - Arrays.sort((long[]) a); - } else if (a instanceof byte[]) { - Arrays.sort((byte[]) a); - } else if (a instanceof char[]) { - Arrays.sort((char[]) a); - } else if (a instanceof short[]) { - Arrays.sort((short[]) a); - } else if (a instanceof float[]) { - Arrays.sort((float[]) a); - } else if (a instanceof double[]) { - Arrays.sort((double[]) a); - } else { - fail(a); - } - } - - @Override - public void sort(Object a, int low, int high) { - if (a instanceof int[]) { - Arrays.sort((int[]) a, low, high); - } else if (a instanceof long[]) { - Arrays.sort((long[]) a, low, high); - } else if (a instanceof byte[]) { - Arrays.sort((byte[]) a, low, high); - } else if (a instanceof char[]) { - Arrays.sort((char[]) a, low, high); - } else if (a instanceof short[]) { - Arrays.sort((short[]) a, low, high); - } else if (a instanceof float[]) { - Arrays.sort((float[]) a, low, high); - } else if (a instanceof double[]) { - Arrays.sort((double[]) a, low, high); - } else { - fail(a); - } - } - - @Override - public void sort(Object[] a) { - Arrays.sort(a); - } - - @Override - @SuppressWarnings("unchecked") - public void sort(Object[] a, Comparator comparator) { - Arrays.sort(a, comparator); - } - }, - - ARRAYS_PARALLEL_SORT("Arrays.parallelSort") { - - @Override - public void sort(Object a) { - if (a instanceof int[]) { - Arrays.parallelSort((int[]) a); - } else if (a instanceof long[]) { - Arrays.parallelSort((long[]) a); - } else if (a instanceof byte[]) { - Arrays.parallelSort((byte[]) a); - } else if (a instanceof char[]) { - Arrays.parallelSort((char[]) a); - } else if (a instanceof short[]) { - Arrays.parallelSort((short[]) a); - } else if (a instanceof float[]) { - Arrays.parallelSort((float[]) a); - } else if (a instanceof double[]) { - Arrays.parallelSort((double[]) a); - } else { - fail(a); - } - } - - @Override - public void sort(Object a, int low, int high) { - if (a instanceof int[]) { - Arrays.parallelSort((int[]) a, low, high); - } else if (a instanceof long[]) { - Arrays.parallelSort((long[]) a, low, high); - } else if (a instanceof byte[]) { - Arrays.parallelSort((byte[]) a, low, high); - } else if (a instanceof char[]) { - Arrays.parallelSort((char[]) a, low, high); - } else if (a instanceof short[]) { - Arrays.parallelSort((short[]) a, low, high); - } else if (a instanceof float[]) { - Arrays.parallelSort((float[]) a, low, high); - } else if (a instanceof double[]) { - Arrays.parallelSort((double[]) a, low, high); - } else { - fail(a); - } - } - - @Override - @SuppressWarnings("unchecked") - public void sort(Object[] a) { - Arrays.parallelSort((Comparable[]) a); - } - - @Override - @SuppressWarnings("unchecked") - public void sort(Object[] a, Comparator comparator) { - Arrays.parallelSort(a, comparator); - } - }; - - abstract public void sort(Object a); - - abstract public void sort(Object a, int low, int high); - - abstract public void sort(Object[] a); - - abstract public void sort(Object[] a, Comparator comparator); - - private SortingHelper(String name) { - this.name = name; - } - - @Override - public String toString() { - return name; - } - - private static void fail(Object a) { - throw new RuntimeException("Unexpected type of array: " + a.getClass().getName()); - } - - private String name; - - /** - * Parallelism level for sequential and parallel sorting. - */ - private static final int SEQUENTIAL = 0; - private static final int PARALLEL = 87; - - /** - * Heap sort will be invoked, if recursion depth is too big. - * Value is taken from DualPivotQuicksort.MAX_RECURSION_DEPTH. - */ - private static final int BIG_DEPTH = 64 * (3 << 1); -} +/* + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. 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. + * + * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.util; + +/** + * This class provides access to package-private + * methods of DualPivotQuicksort class. + * + * @author Vladimir Yaroslavskiy + * + * @version 2022.06.14 + * + * @since 14 ^ 22 + */ +public enum SortingHelper { + + DUAL_PIVOT_QUICKSORT("Dual-Pivot Quicksort") { + @Override + public void sort(Object a, int low, int high) { + sort(a, SEQUENTIAL, low, high); + } + }, + + PARALLEL_SORT("Parallel sort") { + @Override + public void sort(Object a, int low, int high) { + sort(a, PARALLEL, low, high); + } + }, + + MIXED_INSERTION_SORT("Mixed insertion sort") { + @Override + public void sort(Object a, int low, int high) { + if (a instanceof int[]) { + DualPivotQuicksort.mixedInsertionSort((int[]) a, low, high); + } else if (a instanceof long[]) { + DualPivotQuicksort.mixedInsertionSort((long[]) a, low, high); + } else if (a instanceof byte[]) { + DualPivotQuicksort.sort((byte[]) a, low, high); + } else if (a instanceof char[]) { + DualPivotQuicksort.sort((char[]) a, low, high); + } else if (a instanceof short[]) { + DualPivotQuicksort.sort((short[]) a, low, high); + } else if (a instanceof float[]) { + DualPivotQuicksort.mixedInsertionSort((float[]) a, low, high); + } else if (a instanceof double[]) { + DualPivotQuicksort.mixedInsertionSort((double[]) a, low, high); + } else { + fail(a); + } + } + }, + + INSERTION_SORT("Insertion sort") { + @Override + public void sort(Object a, int low, int high) { + if (a instanceof int[]) { + DualPivotQuicksort.insertionSort((int[]) a, low, high); + } else if (a instanceof long[]) { + DualPivotQuicksort.insertionSort((long[]) a, low, high); + } else if (a instanceof byte[]) { + DualPivotQuicksort.insertionSort((byte[]) a, low, high); + } else if (a instanceof char[]) { + DualPivotQuicksort.insertionSort((char[]) a, low, high); + } else if (a instanceof short[]) { + DualPivotQuicksort.insertionSort((short[]) a, low, high); + } else if (a instanceof float[]) { + DualPivotQuicksort.insertionSort((float[]) a, low, high); + } else if (a instanceof double[]) { + DualPivotQuicksort.insertionSort((double[]) a, low, high); + } else { + fail(a); + } + } + }, + + MERGING_SORT("Merging sort") { + @Override + public void sort(Object a, int low, int high) { + if (a instanceof int[]) { + check("Merging", DualPivotQuicksort.tryMergingSort(null, (int[]) a, low, high - low)); + } else if (a instanceof long[]) { + check("Merging", DualPivotQuicksort.tryMergingSort(null, (long[]) a, low, high - low)); + } else if (a instanceof byte[]) { + DualPivotQuicksort.sort((byte[]) a, low, high); + } else if (a instanceof char[]) { + DualPivotQuicksort.sort((char[]) a, low, high); + } else if (a instanceof short[]) { + DualPivotQuicksort.sort((short[]) a, low, high); + } else if (a instanceof float[]) { + check("Merging", DualPivotQuicksort.tryMergingSort(null, (float[]) a, low, high - low)); + } else if (a instanceof double[]) { + check("Merging", DualPivotQuicksort.tryMergingSort(null, (double[]) a, low, high - low)); + } else { + fail(a); + } + } + }, + + RADIX_SORT("Radix sort") { + @Override + public void sort(Object a, int low, int high) { + if (a instanceof int[]) { + check("Radix", DualPivotQuicksort.tryRadixSort(null, (int[]) a, low, high)); + } else if (a instanceof long[]) { + check("Radix", DualPivotQuicksort.tryRadixSort(null, (long[]) a, low, high)); + } else if (a instanceof byte[]) { + DualPivotQuicksort.sort((byte[]) a, low, high); + } else if (a instanceof char[]) { + DualPivotQuicksort.sort((char[]) a, low, high); + } else if (a instanceof short[]) { + DualPivotQuicksort.sort((short[]) a, low, high); + } else if (a instanceof float[]) { + check("Radix", DualPivotQuicksort.tryRadixSort(null, (float[]) a, low, high)); + } else if (a instanceof double[]) { + check("Radix", DualPivotQuicksort.tryRadixSort(null, (double[]) a, low, high)); + } else { + fail(a); + } + } + }, + + HEAP_SORT("Heap sort") { + @Override + public void sort(Object a, int low, int high) { + if (a instanceof int[]) { + DualPivotQuicksort.heapSort((int[]) a, low, high); + } else if (a instanceof long[]) { + DualPivotQuicksort.heapSort((long[]) a, low, high); + } else if (a instanceof byte[]) { + DualPivotQuicksort.sort((byte[]) a, low, high); + } else if (a instanceof char[]) { + DualPivotQuicksort.sort((char[]) a, low, high); + } else if (a instanceof short[]) { + DualPivotQuicksort.sort((short[]) a, low, high); + } else if (a instanceof float[]) { + DualPivotQuicksort.heapSort((float[]) a, low, high); + } else if (a instanceof double[]) { + DualPivotQuicksort.heapSort((double[]) a, low, high); + } else { + fail(a); + } + } + }, + + ARRAYS_SORT("Arrays.sort") { + @Override + public void sort(Object a) { + if (a instanceof int[]) { + Arrays.sort((int[]) a); + } else if (a instanceof long[]) { + Arrays.sort((long[]) a); + } else if (a instanceof byte[]) { + Arrays.sort((byte[]) a); + } else if (a instanceof char[]) { + Arrays.sort((char[]) a); + } else if (a instanceof short[]) { + Arrays.sort((short[]) a); + } else if (a instanceof float[]) { + Arrays.sort((float[]) a); + } else if (a instanceof double[]) { + Arrays.sort((double[]) a); + } else { + fail(a); + } + } + + @Override + public void sort(Object a, int low, int high) { + if (a instanceof int[]) { + Arrays.sort((int[]) a, low, high); + } else if (a instanceof long[]) { + Arrays.sort((long[]) a, low, high); + } else if (a instanceof byte[]) { + Arrays.sort((byte[]) a, low, high); + } else if (a instanceof char[]) { + Arrays.sort((char[]) a, low, high); + } else if (a instanceof short[]) { + Arrays.sort((short[]) a, low, high); + } else if (a instanceof float[]) { + Arrays.sort((float[]) a, low, high); + } else if (a instanceof double[]) { + Arrays.sort((double[]) a, low, high); + } else { + fail(a); + } + } + }, + + ARRAYS_PARALLEL_SORT("Arrays.parallelSort") { + @Override + public void sort(Object a) { + if (a instanceof int[]) { + Arrays.parallelSort((int[]) a); + } else if (a instanceof long[]) { + Arrays.parallelSort((long[]) a); + } else if (a instanceof byte[]) { + Arrays.parallelSort((byte[]) a); + } else if (a instanceof char[]) { + Arrays.parallelSort((char[]) a); + } else if (a instanceof short[]) { + Arrays.parallelSort((short[]) a); + } else if (a instanceof float[]) { + Arrays.parallelSort((float[]) a); + } else if (a instanceof double[]) { + Arrays.parallelSort((double[]) a); + } else { + fail(a); + } + } + + @Override + public void sort(Object a, int low, int high) { + if (a instanceof int[]) { + Arrays.parallelSort((int[]) a, low, high); + } else if (a instanceof long[]) { + Arrays.parallelSort((long[]) a, low, high); + } else if (a instanceof byte[]) { + Arrays.parallelSort((byte[]) a, low, high); + } else if (a instanceof char[]) { + Arrays.parallelSort((char[]) a, low, high); + } else if (a instanceof short[]) { + Arrays.parallelSort((short[]) a, low, high); + } else if (a instanceof float[]) { + Arrays.parallelSort((float[]) a, low, high); + } else if (a instanceof double[]) { + Arrays.parallelSort((double[]) a, low, high); + } else { + fail(a); + } + } + }; + + abstract public void sort(Object a, int low, int high); + + public void sort(Object a) { + if (a instanceof int[]) { + sort(a, 0, ((int[]) a).length); + } else if (a instanceof long[]) { + sort(a, 0, ((long[]) a).length); + } else if (a instanceof byte[]) { + sort(a, 0, ((byte[]) a).length); + } else if (a instanceof char[]) { + sort(a, 0, ((char[]) a).length); + } else if (a instanceof short[]) { + sort(a, 0, ((short[]) a).length); + } else if (a instanceof float[]) { + sort(a, 0, ((float[]) a).length); + } else if (a instanceof double[]) { + sort(a, 0, ((double[]) a).length); + } else { + fail(a); + } + } + + SortingHelper(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } + + static void sort(Object a, int parallelism, int low, int high) { + if (a instanceof int[]) { + DualPivotQuicksort.sort((int[]) a, parallelism, low, high); + } else if (a instanceof long[]) { + DualPivotQuicksort.sort((long[]) a, parallelism, low, high); + } else if (a instanceof byte[]) { + DualPivotQuicksort.sort((byte[]) a, low, high); + } else if (a instanceof char[]) { + DualPivotQuicksort.sort((char[]) a, low, high); + } else if (a instanceof short[]) { + DualPivotQuicksort.sort((short[]) a, low, high); + } else if (a instanceof float[]) { + DualPivotQuicksort.sort((float[]) a, parallelism, low, high); + } else if (a instanceof double[]) { + DualPivotQuicksort.sort((double[]) a, parallelism, low, high); + } else { + fail(a); + } + } + + private static void check(String name, boolean result) { + if (!result) { + fail(name + " sort must return true"); + } + } + + private static void fail(Object a) { + fail("Unknown array: " + a.getClass().getName()); + } + + private static void fail(String message) { + throw new RuntimeException(message); + } + + private final String name; + + /** + * Parallelism level for sequential sorting. + */ + private static final int SEQUENTIAL = 0; + + /** + * Parallelism level for parallel sorting. + */ + private static final int PARALLEL = 88; +} diff --git a/test/micro/org/openjdk/bench/java/util/ArraysSort.java b/test/micro/org/openjdk/bench/java/util/ArraysSort.java new file mode 100644 index 0000000000000..e8de83e012f28 --- /dev/null +++ b/test/micro/org/openjdk/bench/java/util/ArraysSort.java @@ -0,0 +1,311 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. 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. + * + * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package org.openjdk.bench.java.util; + +import java.util.Arrays; +import java.util.Random; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; + +/** + * Microbenchmark for Arrays.sort() and Arrays.parallelSort(). + * + * @author Vladimir Yaroslavskiy + * + * @version 2022.06.14 + * + * @since 22 + */ +@Fork(1) +@State(Scope.Benchmark) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@Warmup(iterations = 1, time = 5, timeUnit = TimeUnit.SECONDS) +@Measurement(iterations = 4, time = 3, timeUnit = TimeUnit.SECONDS) +public class ArraysSort { + + @Param({ "800", "7000", "50000", "300000", "2000000" }) + int size; + + @Param + Builder builder; + + int[] b; + + @Setup + public void init() { + b = new int[size]; + } + + public enum Builder { + + RANDOM { + @Override + void build(int[] b) { + Random random = new Random(0x777); + + for (int i = 0; i < b.length; ++i) { + b[i] = random.nextInt(); + } + } + }, + + REPEATED { + @Override + void build(int[] b) { + Random random = new Random(0x777); + + for (int i = 0; i < b.length; ++i) { + b[i] = random.nextInt(4); + } + } + }, + + STAGGER { + @Override + void build(int[] b) { + for (int i = 0; i < b.length; ++i) { + b[i] = (i * 3) % b.length; + } + } + }, + + SHUFFLE { + @Override + void build(int[] b) { + Random random = new Random(0x777); + + for (int i = 0, j = 0, k = 1; i < b.length; ++i) { + b[i] = random.nextInt(6) > 0 ? (j += 2) : (k += 2); + } + } + }; + + abstract void build(int[] b); + } + + public static class Int extends ArraysSort { + + @Setup(Level.Invocation) + public void build() { + builder.build(b); + } + + @Benchmark + public void testSort() { + Arrays.sort(b); + } + + @Benchmark + public void testParallelSort() { + Arrays.parallelSort(b); + } + } + + public static class Long extends ArraysSort { + + long[] a; + + @Setup + public void setup() { + a = new long[size]; + } + + @Setup(Level.Invocation) + public void build() { + builder.build(b); + + for (int i = 0; i < size; ++i) { + a[i] = b[i]; + } + } + + @Benchmark + public void testSort() { + Arrays.sort(a); + } + + @Benchmark + public void testParallelSort() { + Arrays.parallelSort(a); + } + } + + public static class Byte extends ArraysSort { + + byte[] a; + + @Setup + public void setup() { + a = new byte[size]; + } + + @Setup(Level.Invocation) + public void build() { + builder.build(b); + + for (int i = 0; i < size; ++i) { + a[i] = (byte) b[i]; + } + } + + @Benchmark + public void testSort() { + Arrays.sort(a); + } + + @Benchmark + public void testParallelSort() { + Arrays.parallelSort(a); + } + } + + public static class Char extends ArraysSort { + + char[] a; + + @Setup + public void setup() { + a = new char[size]; + } + + @Setup(Level.Invocation) + public void build() { + builder.build(b); + + for (int i = 0; i < size; ++i) { + a[i] = (char) b[i]; + } + } + + @Benchmark + public void testSort() { + Arrays.sort(a); + } + + @Benchmark + public void testParallelSort() { + Arrays.parallelSort(a); + } + } + + public static class Short extends ArraysSort { + + short[] a; + + @Setup + public void setup() { + a = new short[size]; + } + + @Setup(Level.Invocation) + public void build() { + builder.build(b); + + for (int i = 0; i < size; ++i) { + a[i] = (short) b[i]; + } + } + + @Benchmark + public void testSort() { + Arrays.sort(a); + } + + @Benchmark + public void testParallelSort() { + Arrays.parallelSort(a); + } + } + + public static class Float extends ArraysSort { + + float[] a; + + @Setup + public void setup() { + a = new float[size]; + } + + @Setup(Level.Invocation) + public void build() { + builder.build(b); + + for (int i = 0; i < size; ++i) { + a[i] = b[i]; + } + } + + @Benchmark + public void testSort() { + Arrays.sort(a); + } + + @Benchmark + public void testParallelSort() { + Arrays.parallelSort(a); + } + } + + public static class Double extends ArraysSort { + + double[] a; + + @Setup + public void setup() { + a = new double[size]; + } + + @Setup(Level.Invocation) + public void build() { + builder.build(b); + + for (int i = 0; i < size; ++i) { + a[i] = b[i]; + } + } + + @Benchmark + public void testSort() { + Arrays.sort(a); + } + + @Benchmark + public void testParallelSort() { + Arrays.parallelSort(a); + } + } +}