001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021
022import com.google.common.annotations.GwtCompatible;
023import com.google.common.annotations.VisibleForTesting;
024import com.google.common.base.Function;
025
026import java.util.ArrayList;
027import java.util.Arrays;
028import java.util.Collection;
029import java.util.Collections;
030import java.util.Comparator;
031import java.util.HashSet;
032import java.util.Iterator;
033import java.util.List;
034import java.util.Map;
035import java.util.NoSuchElementException;
036import java.util.SortedMap;
037import java.util.SortedSet;
038import java.util.TreeSet;
039import java.util.concurrent.atomic.AtomicInteger;
040
041import javax.annotation.Nullable;
042
043/**
044 * A comparator, with additional methods to support common operations. This is
045 * an "enriched" version of {@code Comparator}, in the same sense that {@link
046 * FluentIterable} is an enriched {@link Iterable}. For example: <pre>   {@code
047 *
048 *   if (Ordering.from(comparator).reverse().isOrdered(list)) { ... }}</pre>
049 *
050 * The {@link #from(Comparator)} method returns the equivalent {@code Ordering}
051 * instance for a pre-existing comparator. You can also skip the comparator step
052 * and extend {@code Ordering} directly: <pre>   {@code
053 *
054 *   Ordering<String> byLengthOrdering = new Ordering<String>() {
055 *     public int compare(String left, String right) {
056 *       return Ints.compare(left.length(), right.length());
057 *     }
058 *   };}</pre>
059 *
060 * Except as noted, the orderings returned by the factory methods of this
061 * class are serializable if and only if the provided instances that back them
062 * are. For example, if {@code ordering} and {@code function} can themselves be
063 * serialized, then {@code ordering.onResultOf(function)} can as well.
064 *
065 * <p>See the Guava User Guide article on <a href=
066 * "http://code.google.com/p/guava-libraries/wiki/OrderingExplained">
067 * {@code Ordering}</a>.
068 *
069 * @author Jesse Wilson
070 * @author Kevin Bourrillion
071 * @since 2.0 (imported from Google Collections Library)
072 */
073@GwtCompatible
074public abstract class Ordering<T> implements Comparator<T> {
075  // Natural order
076
077  /**
078   * Returns a serializable ordering that uses the natural order of the values.
079   * The ordering throws a {@link NullPointerException} when passed a null
080   * parameter.
081   *
082   * <p>The type specification is {@code <C extends Comparable>}, instead of
083   * the technically correct {@code <C extends Comparable<? super C>>}, to
084   * support legacy types from before Java 5.
085   */
086  @GwtCompatible(serializable = true)
087  @SuppressWarnings("unchecked") // TODO(kevinb): right way to explain this??
088  public static <C extends Comparable> Ordering<C> natural() {
089    return (Ordering<C>) NaturalOrdering.INSTANCE;
090  }
091
092  // Static factories
093
094  /**
095   * Returns an ordering based on an <i>existing</i> comparator instance. Note
096   * that there's no need to create a <i>new</i> comparator just to pass it in
097   * here; simply subclass {@code Ordering} and implement its {@code compare}
098   * method directly instead.
099   *
100   * @param comparator the comparator that defines the order
101   * @return comparator itself if it is already an {@code Ordering}; otherwise
102   *     an ordering that wraps that comparator
103   */
104  @GwtCompatible(serializable = true)
105  public static <T> Ordering<T> from(Comparator<T> comparator) {
106    return (comparator instanceof Ordering)
107        ? (Ordering<T>) comparator
108        : new ComparatorOrdering<T>(comparator);
109  }
110
111  /**
112   * Simply returns its argument.
113   *
114   * @deprecated no need to use this
115   */
116  @GwtCompatible(serializable = true)
117  @Deprecated public static <T> Ordering<T> from(Ordering<T> ordering) {
118    return checkNotNull(ordering);
119  }
120
121  /**
122   * Returns an ordering that compares objects according to the order in
123   * which they appear in the given list. Only objects present in the list
124   * (according to {@link Object#equals}) may be compared. This comparator
125   * imposes a "partial ordering" over the type {@code T}. Subsequent changes
126   * to the {@code valuesInOrder} list will have no effect on the returned
127   * comparator. Null values in the list are not supported.
128   *
129   * <p>The returned comparator throws an {@link ClassCastException} when it
130   * receives an input parameter that isn't among the provided values.
131   *
132   * <p>The generated comparator is serializable if all the provided values are
133   * serializable.
134   *
135   * @param valuesInOrder the values that the returned comparator will be able
136   *     to compare, in the order the comparator should induce
137   * @return the comparator described above
138   * @throws NullPointerException if any of the provided values is null
139   * @throws IllegalArgumentException if {@code valuesInOrder} contains any
140   *     duplicate values (according to {@link Object#equals})
141   */
142  @GwtCompatible(serializable = true)
143  public static <T> Ordering<T> explicit(List<T> valuesInOrder) {
144    return new ExplicitOrdering<T>(valuesInOrder);
145  }
146
147  /**
148   * Returns an ordering that compares objects according to the order in
149   * which they are given to this method. Only objects present in the argument
150   * list (according to {@link Object#equals}) may be compared. This comparator
151   * imposes a "partial ordering" over the type {@code T}. Null values in the
152   * argument list are not supported.
153   *
154   * <p>The returned comparator throws a {@link ClassCastException} when it
155   * receives an input parameter that isn't among the provided values.
156   *
157   * <p>The generated comparator is serializable if all the provided values are
158   * serializable.
159   *
160   * @param leastValue the value which the returned comparator should consider
161   *     the "least" of all values
162   * @param remainingValuesInOrder the rest of the values that the returned
163   *     comparator will be able to compare, in the order the comparator should
164   *     follow
165   * @return the comparator described above
166   * @throws NullPointerException if any of the provided values is null
167   * @throws IllegalArgumentException if any duplicate values (according to
168   *     {@link Object#equals(Object)}) are present among the method arguments
169   */
170  @GwtCompatible(serializable = true)
171  public static <T> Ordering<T> explicit(
172      T leastValue, T... remainingValuesInOrder) {
173    return explicit(Lists.asList(leastValue, remainingValuesInOrder));
174  }
175
176  // Ordering<Object> singletons
177
178  /**
179   * Returns an ordering which treats all values as equal, indicating "no
180   * ordering." Passing this ordering to any <i>stable</i> sort algorithm
181   * results in no change to the order of elements. Note especially that {@link
182   * #sortedCopy} and {@link #immutableSortedCopy} are stable, and in the
183   * returned instance these are implemented by simply copying the source list.
184   *
185   * <p>Example: <pre>   {@code
186   *
187   *   Ordering.allEqual().nullsLast().sortedCopy(
188   *       asList(t, null, e, s, null, t, null))}</pre>
189   *
190   * Assuming {@code t}, {@code e} and {@code s} are non-null, this returns
191   * {@code [t, e, s, t, null, null, null]} regardlesss of the true comparison
192   * order of those three values (which might not even implement {@link
193   * Comparable} at all).
194   *
195   * <p><b>Warning:</b> by definition, this comparator is not <i>consistent with
196   * equals</i> (as defined {@linkplain Comparator here}). Avoid its use in
197   * APIs, such as {@link TreeSet#TreeSet(Comparator)}, where such consistency
198   * is expected.
199   *
200   * <p>The returned comparator is serializable.
201   */
202  @GwtCompatible(serializable = true)
203  @SuppressWarnings("unchecked")
204  public static Ordering<Object> allEqual() {
205    return AllEqualOrdering.INSTANCE;
206  }
207
208  /**
209   * Returns an ordering that compares objects by the natural ordering of their
210   * string representations as returned by {@code toString()}. It does not
211   * support null values.
212   *
213   * <p>The comparator is serializable.
214   */
215  @GwtCompatible(serializable = true)
216  public static Ordering<Object> usingToString() {
217    return UsingToStringOrdering.INSTANCE;
218  }
219
220  /**
221   * Returns an arbitrary ordering over all objects, for which {@code compare(a,
222   * b) == 0} implies {@code a == b} (identity equality). There is no meaning
223   * whatsoever to the order imposed, but it is constant for the life of the VM.
224   *
225   * <p>Because the ordering is identity-based, it is not "consistent with
226   * {@link Object#equals(Object)}" as defined by {@link Comparator}. Use
227   * caution when building a {@link SortedSet} or {@link SortedMap} from it, as
228   * the resulting collection will not behave exactly according to spec.
229   *
230   * <p>This ordering is not serializable, as its implementation relies on
231   * {@link System#identityHashCode(Object)}, so its behavior cannot be
232   * preserved across serialization.
233   *
234   * @since 2.0
235   */
236  public static Ordering<Object> arbitrary() {
237    return ArbitraryOrderingHolder.ARBITRARY_ORDERING;
238  }
239
240  private static class ArbitraryOrderingHolder {
241    static final Ordering<Object> ARBITRARY_ORDERING = new ArbitraryOrdering();
242  }
243
244  @VisibleForTesting static class ArbitraryOrdering extends Ordering<Object> {
245    @SuppressWarnings("deprecation") // TODO(kevinb): ?
246    private Map<Object, Integer> uids =
247        Platform.tryWeakKeys(new MapMaker()).makeComputingMap(
248            new Function<Object, Integer>() {
249              final AtomicInteger counter = new AtomicInteger(0);
250              @Override
251              public Integer apply(Object from) {
252                return counter.getAndIncrement();
253              }
254            });
255
256    @Override public int compare(Object left, Object right) {
257      if (left == right) {
258        return 0;
259      } else if (left == null) {
260        return -1;
261      } else if (right == null) {
262        return 1;
263      }
264      int leftCode = identityHashCode(left);
265      int rightCode = identityHashCode(right);
266      if (leftCode != rightCode) {
267        return leftCode < rightCode ? -1 : 1;
268      }
269
270      // identityHashCode collision (rare, but not as rare as you'd think)
271      int result = uids.get(left).compareTo(uids.get(right));
272      if (result == 0) {
273        throw new AssertionError(); // extremely, extremely unlikely.
274      }
275      return result;
276    }
277
278    @Override public String toString() {
279      return "Ordering.arbitrary()";
280    }
281
282    /*
283     * We need to be able to mock identityHashCode() calls for tests, because it
284     * can take 1-10 seconds to find colliding objects. Mocking frameworks that
285     * can do magic to mock static method calls still can't do so for a system
286     * class, so we need the indirection. In production, Hotspot should still
287     * recognize that the call is 1-morphic and should still be willing to
288     * inline it if necessary.
289     */
290    int identityHashCode(Object object) {
291      return System.identityHashCode(object);
292    }
293  }
294
295  // Constructor
296
297  /**
298   * Constructs a new instance of this class (only invokable by the subclass
299   * constructor, typically implicit).
300   */
301  protected Ordering() {}
302
303  // Instance-based factories (and any static equivalents)
304
305  /**
306   * Returns the reverse of this ordering; the {@code Ordering} equivalent to
307   * {@link Collections#reverseOrder(Comparator)}.
308   */
309  // type parameter <S> lets us avoid the extra <String> in statements like:
310  // Ordering<String> o = Ordering.<String>natural().reverse();
311  @GwtCompatible(serializable = true)
312  public <S extends T> Ordering<S> reverse() {
313    return new ReverseOrdering<S>(this);
314  }
315
316  /**
317   * Returns an ordering that treats {@code null} as less than all other values
318   * and uses {@code this} to compare non-null values.
319   */
320  // type parameter <S> lets us avoid the extra <String> in statements like:
321  // Ordering<String> o = Ordering.<String>natural().nullsFirst();
322  @GwtCompatible(serializable = true)
323  public <S extends T> Ordering<S> nullsFirst() {
324    return new NullsFirstOrdering<S>(this);
325  }
326
327  /**
328   * Returns an ordering that treats {@code null} as greater than all other
329   * values and uses this ordering to compare non-null values.
330   */
331  // type parameter <S> lets us avoid the extra <String> in statements like:
332  // Ordering<String> o = Ordering.<String>natural().nullsLast();
333  @GwtCompatible(serializable = true)
334  public <S extends T> Ordering<S> nullsLast() {
335    return new NullsLastOrdering<S>(this);
336  }
337
338  /**
339   * Returns a new ordering on {@code F} which orders elements by first applying
340   * a function to them, then comparing those results using {@code this}. For
341   * example, to compare objects by their string forms, in a case-insensitive
342   * manner, use: <pre>   {@code
343   *
344   *   Ordering.from(String.CASE_INSENSITIVE_ORDER)
345   *       .onResultOf(Functions.toStringFunction())}</pre>
346   */
347  @GwtCompatible(serializable = true)
348  public <F> Ordering<F> onResultOf(Function<F, ? extends T> function) {
349    return new ByFunctionOrdering<F, T>(function, this);
350  }
351  
352  <T2 extends T> Ordering<Map.Entry<T2, ?>> onKeys() {
353    return onResultOf(Maps.<T2>keyFunction());
354  }
355
356  /**
357   * Returns an ordering which first uses the ordering {@code this}, but which
358   * in the event of a "tie", then delegates to {@code secondaryComparator}.
359   * For example, to sort a bug list first by status and second by priority, you
360   * might use {@code byStatus.compound(byPriority)}. For a compound ordering
361   * with three or more components, simply chain multiple calls to this method.
362   *
363   * <p>An ordering produced by this method, or a chain of calls to this method,
364   * is equivalent to one created using {@link Ordering#compound(Iterable)} on
365   * the same component comparators.
366   */
367  @GwtCompatible(serializable = true)
368  public <U extends T> Ordering<U> compound(
369      Comparator<? super U> secondaryComparator) {
370    return new CompoundOrdering<U>(this, checkNotNull(secondaryComparator));
371  }
372
373  /**
374   * Returns an ordering which tries each given comparator in order until a
375   * non-zero result is found, returning that result, and returning zero only if
376   * all comparators return zero. The returned ordering is based on the state of
377   * the {@code comparators} iterable at the time it was provided to this
378   * method.
379   *
380   * <p>The returned ordering is equivalent to that produced using {@code
381   * Ordering.from(comp1).compound(comp2).compound(comp3) . . .}.
382   *
383   * <p><b>Warning:</b> Supplying an argument with undefined iteration order,
384   * such as a {@link HashSet}, will produce non-deterministic results.
385   *
386   * @param comparators the comparators to try in order
387   */
388  @GwtCompatible(serializable = true)
389  public static <T> Ordering<T> compound(
390      Iterable<? extends Comparator<? super T>> comparators) {
391    return new CompoundOrdering<T>(comparators);
392  }
393
394  /**
395   * Returns a new ordering which sorts iterables by comparing corresponding
396   * elements pairwise until a nonzero result is found; imposes "dictionary
397   * order". If the end of one iterable is reached, but not the other, the
398   * shorter iterable is considered to be less than the longer one. For example,
399   * a lexicographical natural ordering over integers considers {@code
400   * [] < [1] < [1, 1] < [1, 2] < [2]}.
401   *
402   * <p>Note that {@code ordering.lexicographical().reverse()} is not
403   * equivalent to {@code ordering.reverse().lexicographical()} (consider how
404   * each would order {@code [1]} and {@code [1, 1]}).
405   *
406   * @since 2.0
407   */
408  @GwtCompatible(serializable = true)
409  // type parameter <S> lets us avoid the extra <String> in statements like:
410  // Ordering<Iterable<String>> o =
411  //     Ordering.<String>natural().lexicographical();
412  public <S extends T> Ordering<Iterable<S>> lexicographical() {
413    /*
414     * Note that technically the returned ordering should be capable of
415     * handling not just {@code Iterable<S>} instances, but also any {@code
416     * Iterable<? extends S>}. However, the need for this comes up so rarely
417     * that it doesn't justify making everyone else deal with the very ugly
418     * wildcard.
419     */
420    return new LexicographicalOrdering<S>(this);
421  }
422
423  // Regular instance methods
424
425  // Override to add @Nullable
426  @Override public abstract int compare(@Nullable T left, @Nullable T right);
427
428  /**
429   * Returns the least of the specified values according to this ordering. If
430   * there are multiple least values, the first of those is returned. The
431   * iterator will be left exhausted: its {@code hasNext()} method will return
432   * {@code false}.
433   *
434   * @param iterator the iterator whose minimum element is to be determined
435   * @throws NoSuchElementException if {@code iterator} is empty
436   * @throws ClassCastException if the parameters are not <i>mutually
437   *     comparable</i> under this ordering.
438   *
439   * @since 11.0
440   */
441  public <E extends T> E min(Iterator<E> iterator) {
442    // let this throw NoSuchElementException as necessary
443    E minSoFar = iterator.next();
444
445    while (iterator.hasNext()) {
446      minSoFar = min(minSoFar, iterator.next());
447    }
448
449    return minSoFar;
450  }
451
452  /**
453   * Returns the least of the specified values according to this ordering. If
454   * there are multiple least values, the first of those is returned.
455   *
456   * @param iterable the iterable whose minimum element is to be determined
457   * @throws NoSuchElementException if {@code iterable} is empty
458   * @throws ClassCastException if the parameters are not <i>mutually
459   *     comparable</i> under this ordering.
460   */
461  public <E extends T> E min(Iterable<E> iterable) {
462    return min(iterable.iterator());
463  }
464
465  /**
466   * Returns the lesser of the two values according to this ordering. If the
467   * values compare as 0, the first is returned.
468   *
469   * <p><b>Implementation note:</b> this method is invoked by the default
470   * implementations of the other {@code min} overloads, so overriding it will
471   * affect their behavior.
472   *
473   * @param a value to compare, returned if less than or equal to b.
474   * @param b value to compare.
475   * @throws ClassCastException if the parameters are not <i>mutually
476   *     comparable</i> under this ordering.
477   */
478  public <E extends T> E min(@Nullable E a, @Nullable E b) {
479    return (compare(a, b) <= 0) ? a : b;
480  }
481
482  /**
483   * Returns the least of the specified values according to this ordering. If
484   * there are multiple least values, the first of those is returned.
485   *
486   * @param a value to compare, returned if less than or equal to the rest.
487   * @param b value to compare
488   * @param c value to compare
489   * @param rest values to compare
490   * @throws ClassCastException if the parameters are not <i>mutually
491   *     comparable</i> under this ordering.
492   */
493  public <E extends T> E min(
494      @Nullable E a, @Nullable E b, @Nullable E c, E... rest) {
495    E minSoFar = min(min(a, b), c);
496
497    for (E r : rest) {
498      minSoFar = min(minSoFar, r);
499    }
500
501    return minSoFar;
502  }
503
504  /**
505   * Returns the greatest of the specified values according to this ordering. If
506   * there are multiple greatest values, the first of those is returned. The
507   * iterator will be left exhausted: its {@code hasNext()} method will return
508   * {@code false}.
509   *
510   * @param iterator the iterator whose maximum element is to be determined
511   * @throws NoSuchElementException if {@code iterator} is empty
512   * @throws ClassCastException if the parameters are not <i>mutually
513   *     comparable</i> under this ordering.
514   *
515   * @since 11.0
516   */
517  public <E extends T> E max(Iterator<E> iterator) {
518    // let this throw NoSuchElementException as necessary
519    E maxSoFar = iterator.next();
520
521    while (iterator.hasNext()) {
522      maxSoFar = max(maxSoFar, iterator.next());
523    }
524
525    return maxSoFar;
526  }
527
528  /**
529   * Returns the greatest of the specified values according to this ordering. If
530   * there are multiple greatest values, the first of those is returned.
531   *
532   * @param iterable the iterable whose maximum element is to be determined
533   * @throws NoSuchElementException if {@code iterable} is empty
534   * @throws ClassCastException if the parameters are not <i>mutually
535   *     comparable</i> under this ordering.
536   */
537  public <E extends T> E max(Iterable<E> iterable) {
538    return max(iterable.iterator());
539  }
540
541  /**
542   * Returns the greater of the two values according to this ordering. If the
543   * values compare as 0, the first is returned.
544   *
545   * <p><b>Implementation note:</b> this method is invoked by the default
546   * implementations of the other {@code max} overloads, so overriding it will
547   * affect their behavior.
548   *
549   * @param a value to compare, returned if greater than or equal to b.
550   * @param b value to compare.
551   * @throws ClassCastException if the parameters are not <i>mutually
552   *     comparable</i> under this ordering.
553   */
554  public <E extends T> E max(@Nullable E a, @Nullable E b) {
555    return (compare(a, b) >= 0) ? a : b;
556  }
557
558  /**
559   * Returns the greatest of the specified values according to this ordering. If
560   * there are multiple greatest values, the first of those is returned.
561   *
562   * @param a value to compare, returned if greater than or equal to the rest.
563   * @param b value to compare
564   * @param c value to compare
565   * @param rest values to compare
566   * @throws ClassCastException if the parameters are not <i>mutually
567   *     comparable</i> under this ordering.
568   */
569  public <E extends T> E max(
570      @Nullable E a, @Nullable E b, @Nullable E c, E... rest) {
571    E maxSoFar = max(max(a, b), c);
572
573    for (E r : rest) {
574      maxSoFar = max(maxSoFar, r);
575    }
576
577    return maxSoFar;
578  }
579
580  /**
581   * Returns the {@code k} least elements of the given iterable according to
582   * this ordering, in order from least to greatest.  If there are fewer than
583   * {@code k} elements present, all will be included.
584   *
585   * <p>The implementation does not necessarily use a <i>stable</i> sorting
586   * algorithm; when multiple elements are equivalent, it is undefined which
587   * will come first.
588   *
589   * @return an immutable {@code RandomAccess} list of the {@code k} least
590   *     elements in ascending order
591   * @throws IllegalArgumentException if {@code k} is negative
592   * @since 8.0
593   */
594  public <E extends T> List<E> leastOf(Iterable<E> iterable, int k) {
595    if (iterable instanceof Collection) {
596      Collection<E> collection = (Collection<E>) iterable;
597      if (collection.size() <= 2L * k) {
598        // In this case, just dumping the collection to an array and sorting is
599        // faster than using the implementation for Iterator, which is
600        // specialized for k much smaller than n.
601
602        @SuppressWarnings("unchecked") // c only contains E's and doesn't escape
603        E[] array = (E[]) collection.toArray();
604        Arrays.sort(array, this);
605        if (array.length > k) {
606          array = ObjectArrays.arraysCopyOf(array, k);
607        }
608        return Collections.unmodifiableList(Arrays.asList(array));
609      }
610    }
611    return leastOf(iterable.iterator(), k);
612  }
613
614  /**
615   * Returns the {@code k} least elements from the given iterator according to
616   * this ordering, in order from least to greatest.  If there are fewer than
617   * {@code k} elements present, all will be included.
618   *
619   * <p>The implementation does not necessarily use a <i>stable</i> sorting
620   * algorithm; when multiple elements are equivalent, it is undefined which
621   * will come first.
622   *
623   * @return an immutable {@code RandomAccess} list of the {@code k} least
624   *     elements in ascending order
625   * @throws IllegalArgumentException if {@code k} is negative
626   * @since 14.0
627   */
628  public <E extends T> List<E> leastOf(Iterator<E> elements, int k) {
629    checkNotNull(elements);
630    checkArgument(k >= 0, "k (%s) must be nonnegative", k);
631
632    if (k == 0 || !elements.hasNext()) {
633      return ImmutableList.of();
634    } else if (k >= Integer.MAX_VALUE / 2) {
635      // k is really large; just do a straightforward sorted-copy-and-sublist
636      ArrayList<E> list = Lists.newArrayList(elements);
637      Collections.sort(list, this);
638      if (list.size() > k) {
639        list.subList(k, list.size()).clear();
640      }
641      list.trimToSize();
642      return Collections.unmodifiableList(list);
643    }
644
645    /*
646     * Our goal is an O(n) algorithm using only one pass and O(k) additional
647     * memory.
648     *
649     * We use the following algorithm: maintain a buffer of size 2*k. Every time
650     * the buffer gets full, find the median and partition around it, keeping
651     * only the lowest k elements.  This requires n/k find-median-and-partition
652     * steps, each of which take O(k) time with a traditional quickselect.
653     *
654     * After sorting the output, the whole algorithm is O(n + k log k). It
655     * degrades gracefully for worst-case input (descending order), performs
656     * competitively or wins outright for randomly ordered input, and doesn't
657     * require the whole collection to fit into memory.
658     */
659    int bufferCap = k * 2;
660    @SuppressWarnings("unchecked") // we'll only put E's in
661    E[] buffer = (E[]) new Object[bufferCap];
662    E threshold = elements.next();
663    buffer[0] = threshold;
664    int bufferSize = 1;
665    // threshold is the kth smallest element seen so far.  Once bufferSize >= k,
666    // anything larger than threshold can be ignored immediately.
667
668    while (bufferSize < k && elements.hasNext()) {
669      E e = elements.next();
670      buffer[bufferSize++] = e;
671      threshold = max(threshold, e);
672    }
673
674    while (elements.hasNext()) {
675      E e = elements.next();
676      if (compare(e, threshold) >= 0) {
677        continue;
678      }
679
680      buffer[bufferSize++] = e;
681      if (bufferSize == bufferCap) {
682        // We apply the quickselect algorithm to partition about the median,
683        // and then ignore the last k elements.
684        int left = 0;
685        int right = bufferCap - 1;
686
687        int minThresholdPosition = 0;
688        // The leftmost position at which the greatest of the k lower elements
689        // -- the new value of threshold -- might be found.
690
691        while (left < right) {
692          int pivotIndex = (left + right + 1) >>> 1;
693          int pivotNewIndex = partition(buffer, left, right, pivotIndex);
694          if (pivotNewIndex > k) {
695            right = pivotNewIndex - 1;
696          } else if (pivotNewIndex < k) {
697            left = Math.max(pivotNewIndex, left + 1);
698            minThresholdPosition = pivotNewIndex;
699          } else {
700            break;
701          }
702        }
703        bufferSize = k;
704
705        threshold = buffer[minThresholdPosition];
706        for (int i = minThresholdPosition + 1; i < bufferSize; i++) {
707          threshold = max(threshold, buffer[i]);
708        }
709      }
710    }
711
712    Arrays.sort(buffer, 0, bufferSize, this);
713
714    bufferSize = Math.min(bufferSize, k);
715    return Collections.unmodifiableList(
716        Arrays.asList(ObjectArrays.arraysCopyOf(buffer, bufferSize)));
717    // We can't use ImmutableList; we have to be null-friendly!
718  }
719
720  private <E extends T> int partition(
721      E[] values, int left, int right, int pivotIndex) {
722    E pivotValue = values[pivotIndex];
723
724    values[pivotIndex] = values[right];
725    values[right] = pivotValue;
726
727    int storeIndex = left;
728    for (int i = left; i < right; i++) {
729      if (compare(values[i], pivotValue) < 0) {
730        ObjectArrays.swap(values, storeIndex, i);
731        storeIndex++;
732      }
733    }
734    ObjectArrays.swap(values, right, storeIndex);
735    return storeIndex;
736  }
737
738  /**
739   * Returns the {@code k} greatest elements of the given iterable according to
740   * this ordering, in order from greatest to least. If there are fewer than
741   * {@code k} elements present, all will be included.
742   *
743   * <p>The implementation does not necessarily use a <i>stable</i> sorting
744   * algorithm; when multiple elements are equivalent, it is undefined which
745   * will come first.
746   *
747   * @return an immutable {@code RandomAccess} list of the {@code k} greatest
748   *     elements in <i>descending order</i>
749   * @throws IllegalArgumentException if {@code k} is negative
750   * @since 8.0
751   */
752  public <E extends T> List<E> greatestOf(Iterable<E> iterable, int k) {
753    // TODO(kevinb): see if delegation is hurting performance noticeably
754    // TODO(kevinb): if we change this implementation, add full unit tests.
755    return reverse().leastOf(iterable, k);
756  }
757
758  /**
759   * Returns the {@code k} greatest elements from the given iterator according to
760   * this ordering, in order from greatest to least. If there are fewer than
761   * {@code k} elements present, all will be included.
762   *
763   * <p>The implementation does not necessarily use a <i>stable</i> sorting
764   * algorithm; when multiple elements are equivalent, it is undefined which
765   * will come first.
766   *
767   * @return an immutable {@code RandomAccess} list of the {@code k} greatest
768   *     elements in <i>descending order</i>
769   * @throws IllegalArgumentException if {@code k} is negative
770   * @since 14.0
771   */
772  public <E extends T> List<E> greatestOf(Iterator<E> iterator, int k) {
773    return reverse().leastOf(iterator, k);
774  }
775
776  /**
777   * Returns a copy of the given iterable sorted by this ordering. The input is
778   * not modified. The returned list is modifiable, serializable, and has random
779   * access.
780   *
781   * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard
782   * elements that are duplicates according to the comparator. The sort
783   * performed is <i>stable</i>, meaning that such elements will appear in the
784   * resulting list in the same order they appeared in the input.
785   *
786   * @param iterable the elements to be copied and sorted
787   * @return a new list containing the given elements in sorted order
788   */
789  public <E extends T> List<E> sortedCopy(Iterable<E> iterable) {
790    @SuppressWarnings("unchecked") // does not escape, and contains only E's
791    E[] array = (E[]) Iterables.toArray(iterable);
792    Arrays.sort(array, this);
793    return Lists.newArrayList(Arrays.asList(array));
794  }
795
796  /**
797   * Returns an <i>immutable</i> copy of the given iterable sorted by this
798   * ordering. The input is not modified.
799   *
800   * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard
801   * elements that are duplicates according to the comparator. The sort
802   * performed is <i>stable</i>, meaning that such elements will appear in the
803   * resulting list in the same order they appeared in the input.
804   *
805   * @param iterable the elements to be copied and sorted
806   * @return a new immutable list containing the given elements in sorted order
807   * @throws NullPointerException if {@code iterable} or any of its elements is
808   *     null
809   * @since 3.0
810   */
811  public <E extends T> ImmutableList<E> immutableSortedCopy(
812      Iterable<E> iterable) {
813    @SuppressWarnings("unchecked") // we'll only ever have E's in here
814    E[] elements = (E[]) Iterables.toArray(iterable);
815    for (E e : elements) {
816      checkNotNull(e);
817    }
818    Arrays.sort(elements, this);
819    return ImmutableList.asImmutableList(elements);
820  }
821
822  /**
823   * Returns {@code true} if each element in {@code iterable} after the first is
824   * greater than or equal to the element that preceded it, according to this
825   * ordering. Note that this is always true when the iterable has fewer than
826   * two elements.
827   */
828  public boolean isOrdered(Iterable<? extends T> iterable) {
829    Iterator<? extends T> it = iterable.iterator();
830    if (it.hasNext()) {
831      T prev = it.next();
832      while (it.hasNext()) {
833        T next = it.next();
834        if (compare(prev, next) > 0) {
835          return false;
836        }
837        prev = next;
838      }
839    }
840    return true;
841  }
842
843  /**
844   * Returns {@code true} if each element in {@code iterable} after the first is
845   * <i>strictly</i> greater than the element that preceded it, according to
846   * this ordering. Note that this is always true when the iterable has fewer
847   * than two elements.
848   */
849  public boolean isStrictlyOrdered(Iterable<? extends T> iterable) {
850    Iterator<? extends T> it = iterable.iterator();
851    if (it.hasNext()) {
852      T prev = it.next();
853      while (it.hasNext()) {
854        T next = it.next();
855        if (compare(prev, next) >= 0) {
856          return false;
857        }
858        prev = next;
859      }
860    }
861    return true;
862  }
863
864  /**
865   * {@link Collections#binarySearch(List, Object, Comparator) Searches}
866   * {@code sortedList} for {@code key} using the binary search algorithm. The
867   * list must be sorted using this ordering.
868   *
869   * @param sortedList the list to be searched
870   * @param key the key to be searched for
871   */
872  public int binarySearch(List<? extends T> sortedList, @Nullable T key) {
873    return Collections.binarySearch(sortedList, key, this);
874  }
875
876  /**
877   * Exception thrown by a {@link Ordering#explicit(List)} or {@link
878   * Ordering#explicit(Object, Object[])} comparator when comparing a value
879   * outside the set of values it can compare. Extending {@link
880   * ClassCastException} may seem odd, but it is required.
881   */
882  // TODO(kevinb): make this public, document it right
883  @VisibleForTesting
884  static class IncomparableValueException extends ClassCastException {
885    final Object value;
886
887    IncomparableValueException(Object value) {
888      super("Cannot compare value: " + value);
889      this.value = value;
890    }
891
892    private static final long serialVersionUID = 0;
893  }
894
895  // Never make these public
896  static final int LEFT_IS_GREATER = 1;
897  static final int RIGHT_IS_GREATER = -1;
898}