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    
017    package com.google.common.collect;
018    
019    import static com.google.common.base.Preconditions.checkArgument;
020    import static com.google.common.base.Preconditions.checkNotNull;
021    
022    import com.google.common.annotations.Beta;
023    import com.google.common.annotations.GwtCompatible;
024    import com.google.common.annotations.VisibleForTesting;
025    import com.google.common.base.Function;
026    
027    import java.util.Arrays;
028    import java.util.Collections;
029    import java.util.Comparator;
030    import java.util.HashSet;
031    import java.util.Iterator;
032    import java.util.List;
033    import java.util.Map;
034    import java.util.NoSuchElementException;
035    import java.util.SortedMap;
036    import java.util.SortedSet;
037    import java.util.TreeSet;
038    import java.util.concurrent.atomic.AtomicInteger;
039    
040    import javax.annotation.Nullable;
041    
042    /**
043     * A comparator, with additional methods to support common operations. This is
044     * an "enriched" version of {@code Comparator}, in the same sense that {@link
045     * FluentIterable} is an enriched {@link Iterable}). For example: <pre>   {@code
046     *
047     *   if (Ordering.from(comparator).reverse().isOrdered(list)) { ... }}</pre>
048     *
049     * The {@link #from(Comparator)} method returns the equivalent {@code Ordering}
050     * instance for a pre-existing comparator. You can also skip the comparator step
051     * and extend {@code Ordering} directly: <pre>   {@code
052     *
053     *   Ordering<String> byLengthOrdering = new Ordering<String>() {
054     *     public int compare(String left, String right) {
055     *       return Ints.compare(left.length(), right.length());
056     *     }
057     *   };}</pre>
058     *
059     * Except as noted, the orderings returned by the factory methods of this
060     * class are serializable if and only if the provided instances that back them
061     * are. For example, if {@code ordering} and {@code function} can themselves be
062     * serialized, then {@code ordering.onResultOf(function)} can as well.
063     *
064     * <p>See the Guava User Guide article on <a href=
065     * "http://code.google.com/p/guava-libraries/wiki/OrderingExplained">
066     * {@code Ordering}</a>.
067     *
068     * @author Jesse Wilson
069     * @author Kevin Bourrillion
070     * @since 2.0 (imported from Google Collections Library)
071     */
072    @GwtCompatible
073    public abstract class Ordering<T> implements Comparator<T> {
074      // Natural order
075    
076      /**
077       * Returns a serializable ordering that uses the natural order of the values.
078       * The ordering throws a {@link NullPointerException} when passed a null
079       * parameter.
080       *
081       * <p>The type specification is {@code <C extends Comparable>}, instead of
082       * the technically correct {@code <C extends Comparable<? super C>>}, to
083       * support legacy types from before Java 5.
084       */
085      @GwtCompatible(serializable = true)
086      @SuppressWarnings("unchecked") // TODO(kevinb): right way to explain this??
087      public static <C extends Comparable> Ordering<C> natural() {
088        return (Ordering<C>) NaturalOrdering.INSTANCE;
089      }
090    
091      // Static factories
092    
093      /**
094       * Returns an ordering based on an <i>existing</i> comparator instance. Note
095       * that there's no need to create a <i>new</i> comparator just to pass it in
096       * here; simply subclass {@code Ordering} and implement its {@code compareTo}
097       * method directly instead.
098       *
099       * @param comparator the comparator that defines the order
100       * @return comparator itself if it is already an {@code Ordering}; otherwise
101       *     an ordering that wraps that comparator
102       */
103      @GwtCompatible(serializable = true)
104      public static <T> Ordering<T> from(Comparator<T> comparator) {
105        return (comparator instanceof Ordering)
106            ? (Ordering<T>) comparator
107            : new ComparatorOrdering<T>(comparator);
108      }
109    
110      /**
111       * Simply returns its argument.
112       *
113       * @deprecated no need to use this
114       */
115      @GwtCompatible(serializable = true)
116      @Deprecated public static <T> Ordering<T> from(Ordering<T> ordering) {
117        return checkNotNull(ordering);
118      }
119    
120      /**
121       * Returns an ordering that compares objects according to the order in
122       * which they appear in the given list. Only objects present in the list
123       * (according to {@link Object#equals}) may be compared. This comparator
124       * imposes a "partial ordering" over the type {@code T}. Subsequent changes
125       * to the {@code valuesInOrder} list will have no effect on the returned
126       * comparator. Null values in the list are not supported.
127       *
128       * <p>The returned comparator throws an {@link ClassCastException} when it
129       * receives an input parameter that isn't among the provided values.
130       *
131       * <p>The generated comparator is serializable if all the provided values are
132       * serializable.
133       *
134       * @param valuesInOrder the values that the returned comparator will be able
135       *     to compare, in the order the comparator should induce
136       * @return the comparator described above
137       * @throws NullPointerException if any of the provided values is null
138       * @throws IllegalArgumentException if {@code valuesInOrder} contains any
139       *     duplicate values (according to {@link Object#equals})
140       */
141      @GwtCompatible(serializable = true)
142      public static <T> Ordering<T> explicit(List<T> valuesInOrder) {
143        return new ExplicitOrdering<T>(valuesInOrder);
144      }
145    
146      /**
147       * Returns an ordering that compares objects according to the order in
148       * which they are given to this method. Only objects present in the argument
149       * list (according to {@link Object#equals}) may be compared. This comparator
150       * imposes a "partial ordering" over the type {@code T}. Null values in the
151       * argument list are not supported.
152       *
153       * <p>The returned comparator throws a {@link ClassCastException} when it
154       * receives an input parameter that isn't among the provided values.
155       *
156       * <p>The generated comparator is serializable if all the provided values are
157       * serializable.
158       *
159       * @param leastValue the value which the returned comparator should consider
160       *     the "least" of all values
161       * @param remainingValuesInOrder the rest of the values that the returned
162       *     comparator will be able to compare, in the order the comparator should
163       *     follow
164       * @return the comparator described above
165       * @throws NullPointerException if any of the provided values is null
166       * @throws IllegalArgumentException if any duplicate values (according to
167       *     {@link Object#equals(Object)}) are present among the method arguments
168       */
169      @GwtCompatible(serializable = true)
170      public static <T> Ordering<T> explicit(
171          T leastValue, T... remainingValuesInOrder) {
172        return explicit(Lists.asList(leastValue, remainingValuesInOrder));
173      }
174    
175      // Ordering<Object> singletons
176    
177      /**
178       * Returns an ordering which treats all values as equal, indicating "no
179       * ordering." Passing this ordering to any <i>stable</i> sort algorithm
180       * results in no change to the order of elements. Note especially that {@link
181       * #sortedCopy} and {@link #immutableSortedCopy} are stable, and in the
182       * returned instance these are implemented by simply copying the source list.
183       *
184       * <p>Example: <pre>   {@code
185       *
186       *   Ordering.allEqual().nullsLast().sortedCopy(
187       *       asList(t, null, e, s, null, t, null))}</pre>
188       *
189       * Assuming {@code t}, {@code e} and {@code s} are non-null, this returns
190       * {@code [t, e, s, t, null, null, null]} regardlesss of the true comparison
191       * order of those three values (which might not even implement {@link
192       * Comparable} at all).
193       *
194       * <p><b>Warning:</b> by definition, this comparator is not <i>consistent with
195       * equals</i> (as defined {@linkplain Comparator here}). Avoid its use in
196       * APIs, such as {@link TreeSet#TreeSet(Comparator)}, where such consistency
197       * is expected.
198       *
199       * <p>The returned comparator is serializable.
200       */
201      @GwtCompatible(serializable = true)
202      @SuppressWarnings("unchecked")
203      public static Ordering<Object> allEqual() {
204        return AllEqualOrdering.INSTANCE;
205      }
206    
207      /**
208       * Returns an ordering that compares objects by the natural ordering of their
209       * string representations as returned by {@code toString()}. It does not
210       * support null values.
211       *
212       * <p>The comparator is serializable.
213       */
214      @GwtCompatible(serializable = true)
215      public static Ordering<Object> usingToString() {
216        return UsingToStringOrdering.INSTANCE;
217      }
218    
219      /**
220       * Returns an arbitrary ordering over all objects, for which {@code compare(a,
221       * b) == 0} implies {@code a == b} (identity equality). There is no meaning
222       * whatsoever to the order imposed, but it is constant for the life of the VM.
223       *
224       * <p>Because the ordering is identity-based, it is not "consistent with
225       * {@link Object#equals(Object)}" as defined by {@link Comparator}. Use
226       * caution when building a {@link SortedSet} or {@link SortedMap} from it, as
227       * the resulting collection will not behave exactly according to spec.
228       *
229       * <p>This ordering is not serializable, as its implementation relies on
230       * {@link System#identityHashCode(Object)}, so its behavior cannot be
231       * preserved across serialization.
232       *
233       * @since 2.0
234       */
235      public static Ordering<Object> arbitrary() {
236        return ArbitraryOrderingHolder.ARBITRARY_ORDERING;
237      }
238    
239      private static class ArbitraryOrderingHolder {
240        static final Ordering<Object> ARBITRARY_ORDERING = new ArbitraryOrdering();
241      }
242    
243      @VisibleForTesting static class ArbitraryOrdering extends Ordering<Object> {
244        @SuppressWarnings("deprecation") // TODO(kevinb): ?
245        private Map<Object, Integer> uids =
246            Platform.tryWeakKeys(new MapMaker()).makeComputingMap(
247                new Function<Object, Integer>() {
248                  final AtomicInteger counter = new AtomicInteger(0);
249                  public Integer apply(Object from) {
250                    return counter.getAndIncrement();
251                  }
252                });
253    
254        
255        @Override
256        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        
279        @Override
280        public String toString() {
281          return "Ordering.arbitrary()";
282        }
283    
284        /*
285         * We need to be able to mock identityHashCode() calls for tests, because it
286         * can take 1-10 seconds to find colliding objects. Mocking frameworks that
287         * can do magic to mock static method calls still can't do so for a system
288         * class, so we need the indirection. In production, Hotspot should still
289         * recognize that the call is 1-morphic and should still be willing to
290         * inline it if necessary.
291         */
292        int identityHashCode(Object object) {
293          return System.identityHashCode(object);
294        }
295      }
296    
297      // Constructor
298    
299      /**
300       * Constructs a new instance of this class (only invokable by the subclass
301       * constructor, typically implicit).
302       */
303      protected Ordering() {}
304    
305      // Instance-based factories (and any static equivalents)
306    
307      /**
308       * Returns the reverse of this ordering; the {@code Ordering} equivalent to
309       * {@link Collections#reverseOrder(Comparator)}.
310       */
311      // type parameter <S> lets us avoid the extra <String> in statements like:
312      // Ordering<String> o = Ordering.<String>natural().reverse();
313      @GwtCompatible(serializable = true)
314      public <S extends T> Ordering<S> reverse() {
315        return new ReverseOrdering<S>(this);
316      }
317    
318      /**
319       * Returns an ordering that treats {@code null} as less than all other values
320       * and uses {@code this} to compare non-null values.
321       */
322      // type parameter <S> lets us avoid the extra <String> in statements like:
323      // Ordering<String> o = Ordering.<String>natural().nullsFirst();
324      @GwtCompatible(serializable = true)
325      public <S extends T> Ordering<S> nullsFirst() {
326        return new NullsFirstOrdering<S>(this);
327      }
328    
329      /**
330       * Returns an ordering that treats {@code null} as greater than all other
331       * values and uses this ordering to compare non-null values.
332       */
333      // type parameter <S> lets us avoid the extra <String> in statements like:
334      // Ordering<String> o = Ordering.<String>natural().nullsLast();
335      @GwtCompatible(serializable = true)
336      public <S extends T> Ordering<S> nullsLast() {
337        return new NullsLastOrdering<S>(this);
338      }
339    
340      /**
341       * Returns a new ordering on {@code F} which orders elements by first applying
342       * a function to them, then comparing those results using {@code this}. For
343       * example, to compare objects by their string forms, in a case-insensitive
344       * manner, use: <pre>   {@code
345       *
346       *   Ordering.from(String.CASE_INSENSITIVE_ORDER)
347       *       .onResultOf(Functions.toStringFunction())}</pre>
348       */
349      @GwtCompatible(serializable = true)
350      public <F> Ordering<F> onResultOf(Function<F, ? extends T> function) {
351        return new ByFunctionOrdering<F, T>(function, this);
352      }
353    
354      /**
355       * Returns an ordering which first uses the ordering {@code this}, but which
356       * in the event of a "tie", then delegates to {@code secondaryComparator}.
357       * For example, to sort a bug list first by status and second by priority, you
358       * might use {@code byStatus.compound(byPriority)}. For a compound ordering
359       * with three or more components, simply chain multiple calls to this method.
360       *
361       * <p>An ordering produced by this method, or a chain of calls to this method,
362       * is equivalent to one created using {@link Ordering#compound(Iterable)} on
363       * the same component comparators.
364       */
365      @GwtCompatible(serializable = true)
366      public <U extends T> Ordering<U> compound(
367          Comparator<? super U> secondaryComparator) {
368        return new CompoundOrdering<U>(this, checkNotNull(secondaryComparator));
369      }
370    
371      /**
372       * Returns an ordering which tries each given comparator in order until a
373       * non-zero result is found, returning that result, and returning zero only if
374       * all comparators return zero. The returned ordering is based on the state of
375       * the {@code comparators} iterable at the time it was provided to this
376       * method.
377       *
378       * <p>The returned ordering is equivalent to that produced using {@code
379       * Ordering.from(comp1).compound(comp2).compound(comp3) . . .}.
380       *
381       * <p><b>Warning:</b> Supplying an argument with undefined iteration order,
382       * such as a {@link HashSet}, will produce non-deterministic results.
383       *
384       * @param comparators the comparators to try in order
385       */
386      @GwtCompatible(serializable = true)
387      public static <T> Ordering<T> compound(
388          Iterable<? extends Comparator<? super T>> comparators) {
389        return new CompoundOrdering<T>(comparators);
390      }
391    
392      /**
393       * Returns a new ordering which sorts iterables by comparing corresponding
394       * elements pairwise until a nonzero result is found; imposes "dictionary
395       * order". If the end of one iterable is reached, but not the other, the
396       * shorter iterable is considered to be less than the longer one. For example,
397       * a lexicographical natural ordering over integers considers {@code
398       * [] < [1] < [1, 1] < [1, 2] < [2]}.
399       *
400       * <p>Note that {@code ordering.lexicographical().reverse()} is not
401       * equivalent to {@code ordering.reverse().lexicographical()} (consider how
402       * each would order {@code [1]} and {@code [1, 1]}).
403       *
404       * @since 2.0
405       */
406      @GwtCompatible(serializable = true)
407      // type parameter <S> lets us avoid the extra <String> in statements like:
408      // Ordering<Iterable<String>> o =
409      //     Ordering.<String>natural().lexicographical();
410      public <S extends T> Ordering<Iterable<S>> lexicographical() {
411        /*
412         * Note that technically the returned ordering should be capable of
413         * handling not just {@code Iterable<S>} instances, but also any {@code
414         * Iterable<? extends S>}. However, the need for this comes up so rarely
415         * that it doesn't justify making everyone else deal with the very ugly
416         * wildcard.
417         */
418        return new LexicographicalOrdering<S>(this);
419      }
420    
421      // Regular instance methods
422    
423      // Override to add @Nullable
424      public abstract int compare(@Nullable T left, @Nullable T right);
425    
426      /**
427       * Returns the least of the specified values according to this ordering. If
428       * there are multiple least values, the first of those is returned. The
429       * iterator will be left exhausted: its {@code hasNext()} method will return
430       * {@code false}.
431       *
432       * @param iterator the iterator whose minimum element is to be determined
433       * @throws NoSuchElementException if {@code iterator} is empty
434       * @throws ClassCastException if the parameters are not <i>mutually
435       *     comparable</i> under this ordering.
436       *
437       * @since 11.0
438       */
439      @Beta
440      public <E extends T> E min(Iterator<E> iterator) {
441        // let this throw NoSuchElementException as necessary
442        E minSoFar = iterator.next();
443    
444        while (iterator.hasNext()) {
445          minSoFar = min(minSoFar, iterator.next());
446        }
447    
448        return minSoFar;
449      }
450    
451      /**
452       * Returns the least of the specified values according to this ordering. If
453       * there are multiple least values, the first of those is returned.
454       *
455       * @param iterable the iterable whose minimum element is to be determined
456       * @throws NoSuchElementException if {@code iterable} is empty
457       * @throws ClassCastException if the parameters are not <i>mutually
458       *     comparable</i> under this ordering.
459       */
460      public <E extends T> E min(Iterable<E> iterable) {
461        return min(iterable.iterator());
462      }
463    
464      /**
465       * Returns the lesser of the two values according to this ordering. If the
466       * values compare as 0, the first is returned.
467       *
468       * <p><b>Implementation note:</b> this method is invoked by the default
469       * implementations of the other {@code min} overloads, so overriding it will
470       * affect their behavior.
471       *
472       * @param a value to compare, returned if less than or equal to b.
473       * @param b value to compare.
474       * @throws ClassCastException if the parameters are not <i>mutually
475       *     comparable</i> under this ordering.
476       */
477      public <E extends T> E min(@Nullable E a, @Nullable E b) {
478        return compare(a, b) <= 0 ? a : b;
479      }
480    
481      /**
482       * Returns the least of the specified values according to this ordering. If
483       * there are multiple least values, the first of those is returned.
484       *
485       * @param a value to compare, returned if less than or equal to the rest.
486       * @param b value to compare
487       * @param c value to compare
488       * @param rest values to compare
489       * @throws ClassCastException if the parameters are not <i>mutually
490       *     comparable</i> under this ordering.
491       */
492      public <E extends T> E min(
493          @Nullable E a, @Nullable E b, @Nullable E c, E... rest) {
494        E minSoFar = min(min(a, b), c);
495    
496        for (E r : rest) {
497          minSoFar = min(minSoFar, r);
498        }
499    
500        return minSoFar;
501      }
502    
503      /**
504       * Returns the greatest of the specified values according to this ordering. If
505       * there are multiple greatest values, the first of those is returned. The
506       * iterator will be left exhausted: its {@code hasNext()} method will return
507       * {@code false}.
508       *
509       * @param iterator the iterator whose maximum element is to be determined
510       * @throws NoSuchElementException if {@code iterator} is empty
511       * @throws ClassCastException if the parameters are not <i>mutually
512       *     comparable</i> under this ordering.
513       *
514       * @since 11.0
515       */
516      @Beta
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      @Beta
595      public <E extends T> List<E> leastOf(Iterable<E> iterable, int k) {
596        checkArgument(k >= 0, "%d is negative", k);
597    
598        // values is not an E[], but we use it as such for readability. Hack.
599        @SuppressWarnings("unchecked")
600        E[] values = (E[]) Iterables.toArray(iterable);
601    
602        // TODO(nshupe): also sort whole list if k is *near* values.length?
603        // TODO(kevinb): benchmark this impl against hand-coded heap
604        E[] resultArray;
605        if (values.length <= k) {
606          Arrays.sort(values, this);
607          resultArray = values;
608        } else {
609          quicksortLeastK(values, 0, values.length - 1, k);
610    
611          // this is not an E[], but we use it as such for readability. Hack.
612          @SuppressWarnings("unchecked")
613          E[] tmp = (E[]) new Object[k];
614          resultArray = tmp;
615          System.arraycopy(values, 0, resultArray, 0, k);
616        }
617    
618        return Collections.unmodifiableList(Arrays.asList(resultArray));
619      }
620    
621      /**
622       * Returns the {@code k} greatest elements of the given iterable according to
623       * this ordering, in order from greatest to least. If there are fewer than
624       * {@code k} elements present, all will be included.
625       *
626       * <p>The implementation does not necessarily use a <i>stable</i> sorting
627       * algorithm; when multiple elements are equivalent, it is undefined which
628       * will come first.
629       *
630       * @return an immutable {@code RandomAccess} list of the {@code k} greatest
631       *     elements in <i>descending order</i>
632       * @throws IllegalArgumentException if {@code k} is negative
633       * @since 8.0
634       */
635      @Beta
636      public <E extends T> List<E> greatestOf(Iterable<E> iterable, int k) {
637        // TODO(kevinb): see if delegation is hurting performance noticeably
638        // TODO(kevinb): if we change this implementation, add full unit tests.
639        return reverse().leastOf(iterable, k);
640      }
641    
642      private <E extends T> void quicksortLeastK(
643          E[] values, int left, int right, int k) {
644        if (right > left) {
645          int pivotIndex = (left + right) >>> 1; // left + ((right - left) / 2)
646          int pivotNewIndex = partition(values, left, right, pivotIndex);
647          quicksortLeastK(values, left, pivotNewIndex - 1, k);
648          if (pivotNewIndex < k) {
649            quicksortLeastK(values, pivotNewIndex + 1, right, k);
650          }
651        }
652      }
653    
654      private <E extends T> int partition(
655          E[] values, int left, int right, int pivotIndex) {
656        E pivotValue = values[pivotIndex];
657    
658        values[pivotIndex] = values[right];
659        values[right] = pivotValue;
660    
661        int storeIndex = left;
662        for (int i = left; i < right; i++) {
663          if (compare(values[i], pivotValue) < 0) {
664            ObjectArrays.swap(values, storeIndex, i);
665            storeIndex++;
666          }
667        }
668        ObjectArrays.swap(values, right, storeIndex);
669        return storeIndex;
670      }
671    
672      /**
673       * Returns a copy of the given iterable sorted by this ordering. The input is
674       * not modified. The returned list is modifiable, serializable, and has random
675       * access.
676       *
677       * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard
678       * elements that are duplicates according to the comparator. The sort
679       * performed is <i>stable</i>, meaning that such elements will appear in the
680       * resulting list in the same order they appeared in the input.
681       *
682       * @param iterable the elements to be copied and sorted
683       * @return a new list containing the given elements in sorted order
684       */
685      public <E extends T> List<E> sortedCopy(Iterable<E> iterable) {
686        @SuppressWarnings("unchecked") // does not escape, and contains only E's
687        E[] array = (E[]) Iterables.toArray(iterable);
688        Arrays.sort(array, this);
689        return Lists.newArrayList(Arrays.asList(array));
690      }
691    
692      /**
693       * Returns an <i>immutable</i> copy of the given iterable sorted by this
694       * ordering. The input is not modified.
695       *
696       * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard
697       * elements that are duplicates according to the comparator. The sort
698       * performed is <i>stable</i>, meaning that such elements will appear in the
699       * resulting list in the same order they appeared in the input.
700       *
701       * @param iterable the elements to be copied and sorted
702       * @return a new immutable list containing the given elements in sorted order
703       * @throws NullPointerException if {@code iterable} or any of its elements is
704       *     null
705       * @since 3.0
706       */
707      public <E extends T> ImmutableList<E> immutableSortedCopy(
708          Iterable<E> iterable) {
709        @SuppressWarnings("unchecked") // we'll only ever have E's in here
710        E[] elements = (E[]) Iterables.toArray(iterable);
711        for (E e : elements) {
712          checkNotNull(e);
713        }
714        Arrays.sort(elements, this);
715        return ImmutableList.asImmutableList(elements);
716      }
717    
718      /**
719       * Returns {@code true} if each element in {@code iterable} after the first is
720       * greater than or equal to the element that preceded it, according to this
721       * ordering. Note that this is always true when the iterable has fewer than
722       * two elements.
723       */
724      public boolean isOrdered(Iterable<? extends T> iterable) {
725        Iterator<? extends T> it = iterable.iterator();
726        if (it.hasNext()) {
727          T prev = it.next();
728          while (it.hasNext()) {
729            T next = it.next();
730            if (compare(prev, next) > 0) {
731              return false;
732            }
733            prev = next;
734          }
735        }
736        return true;
737      }
738    
739      /**
740       * Returns {@code true} if each element in {@code iterable} after the first is
741       * <i>strictly</i> greater than the element that preceded it, according to
742       * this ordering. Note that this is always true when the iterable has fewer
743       * than two elements.
744       */
745      public boolean isStrictlyOrdered(Iterable<? extends T> iterable) {
746        Iterator<? extends T> it = iterable.iterator();
747        if (it.hasNext()) {
748          T prev = it.next();
749          while (it.hasNext()) {
750            T next = it.next();
751            if (compare(prev, next) >= 0) {
752              return false;
753            }
754            prev = next;
755          }
756        }
757        return true;
758      }
759    
760      /**
761       * {@link Collections#binarySearch(List, Object, Comparator) Searches}
762       * {@code sortedList} for {@code key} using the binary search algorithm. The
763       * list must be sorted using this ordering.
764       *
765       * @param sortedList the list to be searched
766       * @param key the key to be searched for
767       */
768      public int binarySearch(List<? extends T> sortedList, @Nullable T key) {
769        return Collections.binarySearch(sortedList, key, this);
770      }
771    
772      /**
773       * Exception thrown by a {@link Ordering#explicit(List)} or {@link
774       * Ordering#explicit(Object, Object[])} comparator when comparing a value
775       * outside the set of values it can compare. Extending {@link
776       * ClassCastException} may seem odd, but it is required.
777       */
778      // TODO(kevinb): make this public, document it right
779      @VisibleForTesting
780      static class IncomparableValueException extends ClassCastException {
781        final Object value;
782    
783        IncomparableValueException(Object value) {
784          super("Cannot compare value: " + value);
785          this.value = value;
786        }
787    
788        private static final long serialVersionUID = 0;
789      }
790    
791      // Never make these public
792      static final int LEFT_IS_GREATER = 1;
793      static final int RIGHT_IS_GREATER = -1;
794    }