001/*
002 * Copyright (C) 2014 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.math;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static java.lang.Double.NEGATIVE_INFINITY;
019import static java.lang.Double.NaN;
020import static java.lang.Double.POSITIVE_INFINITY;
021import static java.util.Arrays.sort;
022import static java.util.Collections.unmodifiableMap;
023
024import com.google.common.annotations.GwtIncompatible;
025import com.google.common.annotations.J2ktIncompatible;
026import com.google.common.primitives.Doubles;
027import com.google.common.primitives.Ints;
028import java.math.RoundingMode;
029import java.util.Collection;
030import java.util.LinkedHashMap;
031import java.util.Map;
032
033/**
034 * Provides a fluent API for calculating <a
035 * href="http://en.wikipedia.org/wiki/Quantile">quantiles</a>.
036 *
037 * <h2>Examples</h2>
038 *
039 * <p>To compute the median:
040 *
041 * {@snippet :
042 * double myMedian = median().compute(myDataset);
043 * }
044 *
045 * where {@link #median()} has been statically imported.
046 *
047 * <p>To compute the 99th percentile:
048 *
049 * {@snippet :
050 * double myPercentile99 = percentiles().index(99).compute(myDataset);
051 * }
052 *
053 * where {@link #percentiles()} has been statically imported.
054 *
055 * <p>To compute median and the 90th and 99th percentiles:
056 *
057 * {@snippet :
058 * Map<Integer, Double> myPercentiles = percentiles().indexes(50, 90, 99).compute(myDataset);
059 * }
060 *
061 * where {@link #percentiles()} has been statically imported: {@code myPercentiles} maps the keys
062 * 50, 90, and 99, to their corresponding quantile values.
063 *
064 * <p>To compute quartiles, use {@link #quartiles()} instead of {@link #percentiles()}. To compute
065 * arbitrary q-quantiles, use {@link #scale scale(q)}.
066 *
067 * <p>These examples all take a copy of your dataset. If you have a double array, you are okay with
068 * it being arbitrarily reordered, and you want to avoid that copy, you can use {@code
069 * computeInPlace} instead of {@code compute}.
070 *
071 * <h2>Definition and notes on interpolation</h2>
072 *
073 * <p>The definition of the kth q-quantile of N values is as follows: define x = k * (N - 1) / q; if
074 * x is an integer, the result is the value which would appear at index x in the sorted dataset
075 * (unless there are {@link Double#NaN NaN} values, see below); otherwise, the result is the average
076 * of the values which would appear at the indexes floor(x) and ceil(x) weighted by (1-frac(x)) and
077 * frac(x) respectively. This is the same definition as used by Excel and by S, it is the Type 7
078 * definition in <a
079 * href="http://stat.ethz.ch/R-manual/R-devel/library/stats/html/quantile.html">R</a>, and it is
080 * described by <a
081 * href="http://en.wikipedia.org/wiki/Quantile#Estimating_the_quantiles_of_a_population">
082 * wikipedia</a> as providing "Linear interpolation of the modes for the order statistics for the
083 * uniform distribution on [0,1]."
084 *
085 * <h2>Handling of non-finite values</h2>
086 *
087 * <p>If any values in the input are {@link Double#NaN NaN} then all values returned are {@link
088 * Double#NaN NaN}. (This is the one occasion when the behaviour is not the same as you'd get from
089 * sorting with {@link java.util.Arrays#sort(double[]) Arrays.sort(double[])} or {@link
090 * java.util.Collections#sort(java.util.List) Collections.sort(List&lt;Double&gt;)} and selecting
091 * the required value(s). Those methods would sort {@link Double#NaN NaN} as if it is greater than
092 * any other value and place them at the end of the dataset, even after {@link
093 * Double#POSITIVE_INFINITY POSITIVE_INFINITY}.)
094 *
095 * <p>Otherwise, {@link Double#NEGATIVE_INFINITY NEGATIVE_INFINITY} and {@link
096 * Double#POSITIVE_INFINITY POSITIVE_INFINITY} sort to the beginning and the end of the dataset, as
097 * you would expect.
098 *
099 * <p>If required to do a weighted average between an infinity and a finite value, or between an
100 * infinite value and itself, the infinite value is returned. If required to do a weighted average
101 * between {@link Double#NEGATIVE_INFINITY NEGATIVE_INFINITY} and {@link Double#POSITIVE_INFINITY
102 * POSITIVE_INFINITY}, {@link Double#NaN NaN} is returned (note that this will only happen if the
103 * dataset contains no finite values).
104 *
105 * <h2>Performance</h2>
106 *
107 * <p>The average time complexity of the computation is O(N) in the size of the dataset. There is a
108 * worst case time complexity of O(N^2). You are extremely unlikely to hit this quadratic case on
109 * randomly ordered data (the probability decreases faster than exponentially in N), but if you are
110 * passing in unsanitized user data then a malicious user could force it. A light shuffle of the
111 * data using an unpredictable seed should normally be enough to thwart this attack.
112 *
113 * <p>The time taken to compute multiple quantiles on the same dataset using {@link Scale#indexes
114 * indexes} is generally less than the total time taken to compute each of them separately, and
115 * sometimes much less. For example, on a large enough dataset, computing the 90th and 99th
116 * percentiles together takes about 55% as long as computing them separately.
117 *
118 * <p>When calling {@link ScaleAndIndex#compute} (in {@linkplain ScaleAndIndexes#compute either
119 * form}), the memory requirement is 8*N bytes for the copy of the dataset plus an overhead which is
120 * independent of N (but depends on the quantiles being computed). When calling {@link
121 * ScaleAndIndex#computeInPlace computeInPlace} (in {@linkplain ScaleAndIndexes#computeInPlace
122 * either form}), only the overhead is required. The number of object allocations is independent of
123 * N in both cases.
124 *
125 * @author Pete Gillin
126 * @since 20.0
127 */
128@J2ktIncompatible
129@GwtIncompatible
130public final class Quantiles {
131  /**
132   * Constructor for a type that is not meant to be instantiated.
133   *
134   * @deprecated Use the static factory methods of the class. There is no reason to create an
135   *     instance of {@link Quantiles}.
136   */
137  @Deprecated
138  public Quantiles() {}
139
140  /** Specifies the computation of a median (i.e. the 1st 2-quantile). */
141  public static ScaleAndIndex median() {
142    return scale(2).index(1);
143  }
144
145  /** Specifies the computation of quartiles (i.e. 4-quantiles). */
146  public static Scale quartiles() {
147    return scale(4);
148  }
149
150  /** Specifies the computation of percentiles (i.e. 100-quantiles). */
151  public static Scale percentiles() {
152    return scale(100);
153  }
154
155  /**
156   * Specifies the computation of q-quantiles.
157   *
158   * @param scale the scale for the quantiles to be calculated, i.e. the q of the q-quantiles, which
159   *     must be positive
160   */
161  public static Scale scale(int scale) {
162    return new Scale(scale);
163  }
164
165  /**
166   * Describes the point in a fluent API chain where only the scale (i.e. the q in q-quantiles) has
167   * been specified.
168   *
169   * @since 20.0
170   */
171  public static final class Scale {
172
173    private final int scale;
174
175    private Scale(int scale) {
176      checkArgument(scale > 0, "Quantile scale must be positive");
177      this.scale = scale;
178    }
179
180    /**
181     * Specifies a single quantile index to be calculated, i.e. the k in the kth q-quantile.
182     *
183     * @param index the quantile index, which must be in the inclusive range [0, q] for q-quantiles
184     */
185    public ScaleAndIndex index(int index) {
186      return new ScaleAndIndex(scale, index);
187    }
188
189    /**
190     * Specifies multiple quantile indexes to be calculated, each index being the k in the kth
191     * q-quantile.
192     *
193     * @param indexes the quantile indexes, each of which must be in the inclusive range [0, q] for
194     *     q-quantiles; the order of the indexes is unimportant, duplicates will be ignored, and the
195     *     set will be snapshotted when this method is called
196     * @throws IllegalArgumentException if {@code indexes} is empty
197     */
198    public ScaleAndIndexes indexes(int... indexes) {
199      return new ScaleAndIndexes(scale, indexes.clone());
200    }
201
202    /**
203     * Specifies multiple quantile indexes to be calculated, each index being the k in the kth
204     * q-quantile.
205     *
206     * @param indexes the quantile indexes, each of which must be in the inclusive range [0, q] for
207     *     q-quantiles; the order of the indexes is unimportant, duplicates will be ignored, and the
208     *     set will be snapshotted when this method is called
209     * @throws IllegalArgumentException if {@code indexes} is empty
210     */
211    public ScaleAndIndexes indexes(Collection<Integer> indexes) {
212      return new ScaleAndIndexes(scale, Ints.toArray(indexes));
213    }
214  }
215
216  /**
217   * Describes the point in a fluent API chain where the scale and a single quantile index (i.e. the
218   * q and the k in the kth q-quantile) have been specified.
219   *
220   * @since 20.0
221   */
222  public static final class ScaleAndIndex {
223
224    private final int scale;
225    private final int index;
226
227    private ScaleAndIndex(int scale, int index) {
228      checkIndex(index, scale);
229      this.scale = scale;
230      this.index = index;
231    }
232
233    /**
234     * Computes the quantile value of the given dataset.
235     *
236     * @param dataset the dataset to do the calculation on, which must be non-empty, which will be
237     *     cast to doubles (with any associated lost of precision), and which will not be mutated by
238     *     this call (it is copied instead)
239     * @return the quantile value
240     */
241    public double compute(Collection<? extends Number> dataset) {
242      return computeInPlace(Doubles.toArray(dataset));
243    }
244
245    /**
246     * Computes the quantile value of the given dataset.
247     *
248     * @param dataset the dataset to do the calculation on, which must be non-empty, which will not
249     *     be mutated by this call (it is copied instead)
250     * @return the quantile value
251     */
252    public double compute(double... dataset) {
253      return computeInPlace(dataset.clone());
254    }
255
256    /**
257     * Computes the quantile value of the given dataset.
258     *
259     * @param dataset the dataset to do the calculation on, which must be non-empty, which will be
260     *     cast to doubles (with any associated lost of precision), and which will not be mutated by
261     *     this call (it is copied instead)
262     * @return the quantile value
263     */
264    public double compute(long... dataset) {
265      return computeInPlace(longsToDoubles(dataset));
266    }
267
268    /**
269     * Computes the quantile value of the given dataset.
270     *
271     * @param dataset the dataset to do the calculation on, which must be non-empty, which will be
272     *     cast to doubles, and which will not be mutated by this call (it is copied instead)
273     * @return the quantile value
274     */
275    public double compute(int... dataset) {
276      return computeInPlace(intsToDoubles(dataset));
277    }
278
279    /**
280     * Computes the quantile value of the given dataset, performing the computation in-place.
281     *
282     * @param dataset the dataset to do the calculation on, which must be non-empty, and which will
283     *     be arbitrarily reordered by this method call
284     * @return the quantile value
285     */
286    public double computeInPlace(double... dataset) {
287      checkArgument(dataset.length > 0, "Cannot calculate quantiles of an empty dataset");
288      if (containsNaN(dataset)) {
289        return NaN;
290      }
291
292      // Calculate the quotient and remainder in the integer division x = k * (N-1) / q, i.e.
293      // index * (dataset.length - 1) / scale. If there is no remainder, we can just find the value
294      // whose index in the sorted dataset equals the quotient; if there is a remainder, we
295      // interpolate between that and the next value.
296
297      // Since index and (dataset.length - 1) are non-negative ints, their product can be expressed
298      // as a long, without risk of overflow:
299      long numerator = (long) index * (dataset.length - 1);
300      // Since scale is a positive int, index is in [0, scale], and (dataset.length - 1) is a
301      // non-negative int, we can do long-arithmetic on index * (dataset.length - 1) / scale to get
302      // a rounded ratio and a remainder which can be expressed as ints, without risk of overflow:
303      int quotient = (int) LongMath.divide(numerator, scale, RoundingMode.DOWN);
304      int remainder = (int) (numerator - (long) quotient * scale);
305      selectInPlace(quotient, dataset, 0, dataset.length - 1);
306      if (remainder == 0) {
307        return dataset[quotient];
308      } else {
309        selectInPlace(quotient + 1, dataset, quotient + 1, dataset.length - 1);
310        return interpolate(dataset[quotient], dataset[quotient + 1], remainder, scale);
311      }
312    }
313  }
314
315  /**
316   * Describes the point in a fluent API chain where the scale and a multiple quantile indexes (i.e.
317   * the q and a set of values for the k in the kth q-quantile) have been specified.
318   *
319   * @since 20.0
320   */
321  public static final class ScaleAndIndexes {
322
323    private final int scale;
324    private final int[] indexes;
325
326    private ScaleAndIndexes(int scale, int[] indexes) {
327      for (int index : indexes) {
328        checkIndex(index, scale);
329      }
330      checkArgument(indexes.length > 0, "Indexes must be a non empty array");
331      this.scale = scale;
332      this.indexes = indexes;
333    }
334
335    /**
336     * Computes the quantile values of the given dataset.
337     *
338     * @param dataset the dataset to do the calculation on, which must be non-empty, which will be
339     *     cast to doubles (with any associated lost of precision), and which will not be mutated by
340     *     this call (it is copied instead)
341     * @return an unmodifiable, ordered map of results: the keys will be the specified quantile
342     *     indexes, and the values the corresponding quantile values. When iterating, entries in the
343     *     map are ordered by quantile index in the same order they were passed to the {@code
344     *     indexes} method.
345     */
346    public Map<Integer, Double> compute(Collection<? extends Number> dataset) {
347      return computeInPlace(Doubles.toArray(dataset));
348    }
349
350    /**
351     * Computes the quantile values of the given dataset.
352     *
353     * @param dataset the dataset to do the calculation on, which must be non-empty, which will not
354     *     be mutated by this call (it is copied instead)
355     * @return an unmodifiable, ordered map of results: the keys will be the specified quantile
356     *     indexes, and the values the corresponding quantile values. When iterating, entries in the
357     *     map are ordered by quantile index in the same order they were passed to the {@code
358     *     indexes} method.
359     */
360    public Map<Integer, Double> compute(double... dataset) {
361      return computeInPlace(dataset.clone());
362    }
363
364    /**
365     * Computes the quantile values of the given dataset.
366     *
367     * @param dataset the dataset to do the calculation on, which must be non-empty, which will be
368     *     cast to doubles (with any associated lost of precision), and which will not be mutated by
369     *     this call (it is copied instead)
370     * @return an unmodifiable, ordered map of results: the keys will be the specified quantile
371     *     indexes, and the values the corresponding quantile values. When iterating, entries in the
372     *     map are ordered by quantile index in the same order they were passed to the {@code
373     *     indexes} method.
374     */
375    public Map<Integer, Double> compute(long... dataset) {
376      return computeInPlace(longsToDoubles(dataset));
377    }
378
379    /**
380     * Computes the quantile values of the given dataset.
381     *
382     * @param dataset the dataset to do the calculation on, which must be non-empty, which will be
383     *     cast to doubles, and which will not be mutated by this call (it is copied instead)
384     * @return an unmodifiable, ordered map of results: the keys will be the specified quantile
385     *     indexes, and the values the corresponding quantile values. When iterating, entries in the
386     *     map are ordered by quantile index in the same order they were passed to the {@code
387     *     indexes} method.
388     */
389    public Map<Integer, Double> compute(int... dataset) {
390      return computeInPlace(intsToDoubles(dataset));
391    }
392
393    /**
394     * Computes the quantile values of the given dataset, performing the computation in-place.
395     *
396     * @param dataset the dataset to do the calculation on, which must be non-empty, and which will
397     *     be arbitrarily reordered by this method call
398     * @return an unmodifiable, ordered map of results: the keys will be the specified quantile
399     *     indexes, and the values the corresponding quantile values. When iterating, entries in the
400     *     map are ordered by quantile index in the same order that the indexes were passed to the
401     *     {@code indexes} method.
402     */
403    public Map<Integer, Double> computeInPlace(double... dataset) {
404      checkArgument(dataset.length > 0, "Cannot calculate quantiles of an empty dataset");
405      if (containsNaN(dataset)) {
406        Map<Integer, Double> nanMap = new LinkedHashMap<>();
407        for (int index : indexes) {
408          nanMap.put(index, NaN);
409        }
410        return unmodifiableMap(nanMap);
411      }
412
413      // Calculate the quotients and remainders in the integer division x = k * (N - 1) / q, i.e.
414      // index * (dataset.length - 1) / scale for each index in indexes. For each, if there is no
415      // remainder, we can just select the value whose index in the sorted dataset equals the
416      // quotient; if there is a remainder, we interpolate between that and the next value.
417
418      int[] quotients = new int[indexes.length];
419      int[] remainders = new int[indexes.length];
420      // The indexes to select. In the worst case, we'll need one each side of each quantile.
421      int[] requiredSelections = new int[indexes.length * 2];
422      int requiredSelectionsCount = 0;
423      for (int i = 0; i < indexes.length; i++) {
424        // Since index and (dataset.length - 1) are non-negative ints, their product can be
425        // expressed as a long, without risk of overflow:
426        long numerator = (long) indexes[i] * (dataset.length - 1);
427        // Since scale is a positive int, index is in [0, scale], and (dataset.length - 1) is a
428        // non-negative int, we can do long-arithmetic on index * (dataset.length - 1) / scale to
429        // get a rounded ratio and a remainder which can be expressed as ints, without risk of
430        // overflow:
431        int quotient = (int) LongMath.divide(numerator, scale, RoundingMode.DOWN);
432        int remainder = (int) (numerator - (long) quotient * scale);
433        quotients[i] = quotient;
434        remainders[i] = remainder;
435        requiredSelections[requiredSelectionsCount] = quotient;
436        requiredSelectionsCount++;
437        if (remainder != 0) {
438          requiredSelections[requiredSelectionsCount] = quotient + 1;
439          requiredSelectionsCount++;
440        }
441      }
442      sort(requiredSelections, 0, requiredSelectionsCount);
443      selectAllInPlace(
444          requiredSelections, 0, requiredSelectionsCount - 1, dataset, 0, dataset.length - 1);
445      Map<Integer, Double> ret = new LinkedHashMap<>();
446      for (int i = 0; i < indexes.length; i++) {
447        int quotient = quotients[i];
448        int remainder = remainders[i];
449        if (remainder == 0) {
450          ret.put(indexes[i], dataset[quotient]);
451        } else {
452          ret.put(
453              indexes[i], interpolate(dataset[quotient], dataset[quotient + 1], remainder, scale));
454        }
455      }
456      return unmodifiableMap(ret);
457    }
458  }
459
460  /** Returns whether any of the values in {@code dataset} are {@code NaN}. */
461  private static boolean containsNaN(double... dataset) {
462    for (double value : dataset) {
463      if (Double.isNaN(value)) {
464        return true;
465      }
466    }
467    return false;
468  }
469
470  /**
471   * Returns a value a fraction {@code (remainder / scale)} of the way between {@code lower} and
472   * {@code upper}. Assumes that {@code lower <= upper}. Correctly handles infinities (but not
473   * {@code NaN}).
474   */
475  private static double interpolate(double lower, double upper, double remainder, double scale) {
476    if (lower == NEGATIVE_INFINITY) {
477      if (upper == POSITIVE_INFINITY) {
478        // Return NaN when lower == NEGATIVE_INFINITY and upper == POSITIVE_INFINITY:
479        return NaN;
480      }
481      // Return NEGATIVE_INFINITY when NEGATIVE_INFINITY == lower <= upper < POSITIVE_INFINITY:
482      return NEGATIVE_INFINITY;
483    }
484    if (upper == POSITIVE_INFINITY) {
485      // Return POSITIVE_INFINITY when NEGATIVE_INFINITY < lower <= upper == POSITIVE_INFINITY:
486      return POSITIVE_INFINITY;
487    }
488    return lower + (upper - lower) * remainder / scale;
489  }
490
491  private static void checkIndex(int index, int scale) {
492    checkArgument(
493        index >= 0 && index <= scale,
494        "Quantile indexes must be between 0 and the scale, which is %s",
495        scale);
496  }
497
498  private static double[] longsToDoubles(long[] longs) {
499    int len = longs.length;
500    double[] doubles = new double[len];
501    for (int i = 0; i < len; i++) {
502      doubles[i] = longs[i];
503    }
504    return doubles;
505  }
506
507  private static double[] intsToDoubles(int[] ints) {
508    int len = ints.length;
509    double[] doubles = new double[len];
510    for (int i = 0; i < len; i++) {
511      doubles[i] = ints[i];
512    }
513    return doubles;
514  }
515
516  /**
517   * Performs an in-place selection to find the element which would appear at a given index in a
518   * dataset if it were sorted. The following preconditions should hold:
519   *
520   * <ul>
521   *   <li>{@code required}, {@code from}, and {@code to} should all be indexes into {@code array};
522   *   <li>{@code required} should be in the range [{@code from}, {@code to}];
523   *   <li>all the values with indexes in the range [0, {@code from}) should be less than or equal
524   *       to all the values with indexes in the range [{@code from}, {@code to}];
525   *   <li>all the values with indexes in the range ({@code to}, {@code array.length - 1}] should be
526   *       greater than or equal to all the values with indexes in the range [{@code from}, {@code
527   *       to}].
528   * </ul>
529   *
530   * This method will reorder the values with indexes in the range [{@code from}, {@code to}] such
531   * that all the values with indexes in the range [{@code from}, {@code required}) are less than or
532   * equal to the value with index {@code required}, and all the values with indexes in the range
533   * ({@code required}, {@code to}] are greater than or equal to that value. Therefore, the value at
534   * {@code required} is the value which would appear at that index in the sorted dataset.
535   */
536  private static void selectInPlace(int required, double[] array, int from, int to) {
537    // If we are looking for the least element in the range, we can just do a linear search for it.
538    // (We will hit this whenever we are doing quantile interpolation: our first selection finds
539    // the lower value, our second one finds the upper value by looking for the next least element.)
540    if (required == from) {
541      int min = from;
542      for (int index = from + 1; index <= to; index++) {
543        if (array[min] > array[index]) {
544          min = index;
545        }
546      }
547      if (min != from) {
548        swap(array, min, from);
549      }
550      return;
551    }
552
553    // Let's play quickselect! We'll repeatedly partition the range [from, to] containing the
554    // required element, as long as it has more than one element.
555    while (to > from) {
556      int partitionPoint = partition(array, from, to);
557      if (partitionPoint >= required) {
558        to = partitionPoint - 1;
559      }
560      if (partitionPoint <= required) {
561        from = partitionPoint + 1;
562      }
563    }
564  }
565
566  /**
567   * Performs a partition operation on the slice of {@code array} with elements in the range [{@code
568   * from}, {@code to}]. Uses the median of {@code from}, {@code to}, and the midpoint between them
569   * as a pivot. Returns the index which the slice is partitioned around, i.e. if it returns {@code
570   * ret} then we know that the values with indexes in [{@code from}, {@code ret}) are less than or
571   * equal to the value at {@code ret} and the values with indexes in ({@code ret}, {@code to}] are
572   * greater than or equal to that.
573   */
574  private static int partition(double[] array, int from, int to) {
575    // Select a pivot, and move it to the start of the slice i.e. to index from.
576    movePivotToStartOfSlice(array, from, to);
577    double pivot = array[from];
578
579    // Move all elements with indexes in (from, to] which are greater than the pivot to the end of
580    // the array. Keep track of where those elements begin.
581    int partitionPoint = to;
582    for (int i = to; i > from; i--) {
583      if (array[i] > pivot) {
584        swap(array, partitionPoint, i);
585        partitionPoint--;
586      }
587    }
588
589    // We now know that all elements with indexes in (from, partitionPoint] are less than or equal
590    // to the pivot at from, and all elements with indexes in (partitionPoint, to] are greater than
591    // it. We swap the pivot into partitionPoint and we know the array is partitioned around that.
592    swap(array, from, partitionPoint);
593    return partitionPoint;
594  }
595
596  /**
597   * Selects the pivot to use, namely the median of the values at {@code from}, {@code to}, and
598   * halfway between the two (rounded down), from {@code array}, and ensure (by swapping elements if
599   * necessary) that that pivot value appears at the start of the slice i.e. at {@code from}.
600   * Expects that {@code from} is strictly less than {@code to}.
601   */
602  private static void movePivotToStartOfSlice(double[] array, int from, int to) {
603    int mid = (from + to) >>> 1;
604    // We want to make a swap such that either array[to] <= array[from] <= array[mid], or
605    // array[mid] <= array[from] <= array[to]. We know that from < to, so we know mid < to
606    // (although it's possible that mid == from, if to == from + 1). Note that the postcondition
607    // would be impossible to fulfil if mid == to unless we also have array[from] == array[to].
608    boolean toLessThanMid = (array[to] < array[mid]);
609    boolean midLessThanFrom = (array[mid] < array[from]);
610    boolean toLessThanFrom = (array[to] < array[from]);
611    if (toLessThanMid == midLessThanFrom) {
612      // Either array[to] < array[mid] < array[from] or array[from] <= array[mid] <= array[to].
613      swap(array, mid, from);
614    } else if (toLessThanMid != toLessThanFrom) {
615      // Either array[from] <= array[to] < array[mid] or array[mid] <= array[to] < array[from].
616      swap(array, from, to);
617    }
618    // The postcondition now holds. So the median, our chosen pivot, is at from.
619  }
620
621  /**
622   * Performs an in-place selection, like {@link #selectInPlace}, to select all the indexes {@code
623   * allRequired[i]} for {@code i} in the range [{@code requiredFrom}, {@code requiredTo}]. These
624   * indexes must be sorted in the array and must all be in the range [{@code from}, {@code to}].
625   */
626  private static void selectAllInPlace(
627      int[] allRequired, int requiredFrom, int requiredTo, double[] array, int from, int to) {
628    // Choose the first selection to do...
629    int requiredChosen = chooseNextSelection(allRequired, requiredFrom, requiredTo, from, to);
630    int required = allRequired[requiredChosen];
631
632    // ...do the first selection...
633    selectInPlace(required, array, from, to);
634
635    // ...then recursively perform the selections in the range below...
636    int requiredBelow = requiredChosen - 1;
637    while (requiredBelow >= requiredFrom && allRequired[requiredBelow] == required) {
638      requiredBelow--; // skip duplicates of required in the range below
639    }
640    if (requiredBelow >= requiredFrom) {
641      selectAllInPlace(allRequired, requiredFrom, requiredBelow, array, from, required - 1);
642    }
643
644    // ...and then recursively perform the selections in the range above.
645    int requiredAbove = requiredChosen + 1;
646    while (requiredAbove <= requiredTo && allRequired[requiredAbove] == required) {
647      requiredAbove++; // skip duplicates of required in the range above
648    }
649    if (requiredAbove <= requiredTo) {
650      selectAllInPlace(allRequired, requiredAbove, requiredTo, array, required + 1, to);
651    }
652  }
653
654  /**
655   * Chooses the next selection to do from the required selections. It is required that the array
656   * {@code allRequired} is sorted and that {@code allRequired[i]} are in the range [{@code from},
657   * {@code to}] for all {@code i} in the range [{@code requiredFrom}, {@code requiredTo}]. The
658   * value returned by this method is the {@code i} in that range such that {@code allRequired[i]}
659   * is as close as possible to the center of the range [{@code from}, {@code to}]. Choosing the
660   * value closest to the center of the range first is the most efficient strategy because it
661   * minimizes the size of the subranges from which the remaining selections must be done.
662   */
663  private static int chooseNextSelection(
664      int[] allRequired, int requiredFrom, int requiredTo, int from, int to) {
665    if (requiredFrom == requiredTo) {
666      return requiredFrom; // only one thing to choose, so choose it
667    }
668
669    // Find the center and round down. The true center is either centerFloor or halfway between
670    // centerFloor and centerFloor + 1.
671    int centerFloor = (from + to) >>> 1;
672
673    // Do a binary search until we're down to the range of two which encloses centerFloor (unless
674    // all values are lower or higher than centerFloor, in which case we find the two highest or
675    // lowest respectively). If centerFloor is in allRequired, we will definitely find it. If not,
676    // but centerFloor + 1 is, we'll definitely find that. The closest value to the true (unrounded)
677    // center will be at either low or high.
678    int low = requiredFrom;
679    int high = requiredTo;
680    while (high > low + 1) {
681      int mid = (low + high) >>> 1;
682      if (allRequired[mid] > centerFloor) {
683        high = mid;
684      } else if (allRequired[mid] < centerFloor) {
685        low = mid;
686      } else {
687        return mid; // allRequired[mid] = centerFloor, so we can't get closer than that
688      }
689    }
690
691    // Now pick the closest of the two candidates. Note that there is no rounding here.
692    if (from + to - allRequired[low] - allRequired[high] > 0) {
693      return high;
694    } else {
695      return low;
696    }
697  }
698
699  /** Swaps the values at {@code i} and {@code j} in {@code array}. */
700  private static void swap(double[] array, int i, int j) {
701    double temp = array[i];
702    array[i] = array[j];
703    array[j] = temp;
704  }
705}