private static long med3( final boolean x[][], final long a, final long b, final long c, BooleanComparator comp) { int ab = comp.compare(get(x, a), get(x, b)); int ac = comp.compare(get(x, a), get(x, c)); int bc = comp.compare(get(x, b), get(x, c)); return (ab < 0 ? (bc < 0 ? b : ac < 0 ? c : a) : (bc > 0 ? b : ac > 0 ? c : a)); }
/** * Sorts the specified range of elements according to the order induced by the specified * comparator using quicksort. * * <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas * McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, * 23(11), pages 1249−1265, 1993. * * @param x the big array to be sorted. * @param from the index of the first element (inclusive) to be sorted. * @param to the index of the last element (exclusive) to be sorted. * @param comp the comparator to determine the sorting order. */ public static void quickSort( final boolean[][] x, final long from, final long to, final BooleanComparator comp) { final long len = to - from; // Selection sort on smallest arrays if (len < SMALL) { selectionSort(x, from, to, comp); return; } // Choose a partition element, v long m = from + len / 2; // Small arrays, middle element if (len > SMALL) { long l = from; long n = to - 1; if (len > MEDIUM) { // Big arrays, pseudomedian of 9 long s = len / 8; l = med3(x, l, l + s, l + 2 * s, comp); m = med3(x, m - s, m, m + s, comp); n = med3(x, n - 2 * s, n - s, n, comp); } m = med3(x, l, m, n, comp); // Mid-size, med of 3 } final boolean v = get(x, m); // Establish Invariant: v* (<v)* (>v)* v* long a = from, b = a, c = to - 1, d = c; while (true) { int comparison; while (b <= c && (comparison = comp.compare(get(x, b), v)) <= 0) { if (comparison == 0) swap(x, a++, b); b++; } while (c >= b && (comparison = comp.compare(get(x, c), v)) >= 0) { if (comparison == 0) swap(x, c, d--); c--; } if (b > c) break; swap(x, b++, c--); } // Swap partition elements back to middle long s, n = to; s = Math.min(a - from, b - a); vecSwap(x, from, b - s, s); s = Math.min(d - c, n - d - 1); vecSwap(x, b, n - s, s); // Recursively sort non-partition-elements if ((s = b - a) > 1) quickSort(x, from, from + s, comp); if ((s = d - c) > 1) quickSort(x, n - s, n, comp); }
private static void selectionSort( final boolean[][] a, final long from, final long to, final BooleanComparator comp) { for (long i = from; i < to - 1; i++) { long m = i; for (long j = i + 1; j < to; j++) if (comp.compare(BooleanBigArrays.get(a, j), BooleanBigArrays.get(a, m)) < 0) m = j; if (m != i) swap(a, i, m); } }