001/*
002 * Copyright (C) 2010 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;
021import static com.google.common.base.Preconditions.checkPositionIndex;
022import static com.google.common.base.Preconditions.checkState;
023import static com.google.common.collect.CollectPreconditions.checkRemove;
024
025import com.google.common.annotations.Beta;
026import com.google.common.annotations.GwtCompatible;
027import com.google.common.annotations.VisibleForTesting;
028import com.google.common.math.IntMath;
029import com.google.errorprone.annotations.CanIgnoreReturnValue;
030import com.google.j2objc.annotations.Weak;
031import com.google.j2objc.annotations.WeakOuter;
032import java.util.AbstractQueue;
033import java.util.ArrayDeque;
034import java.util.ArrayList;
035import java.util.Collection;
036import java.util.Collections;
037import java.util.Comparator;
038import java.util.ConcurrentModificationException;
039import java.util.Iterator;
040import java.util.List;
041import java.util.NoSuchElementException;
042import java.util.PriorityQueue;
043import java.util.Queue;
044
045/**
046 * A double-ended priority queue, which provides constant-time access to both
047 * its least element and its greatest element, as determined by the queue's
048 * specified comparator. If no comparator is given at creation time, the
049 * natural order of elements is used. If no maximum size is given at creation time,
050 * the queue is unbounded.
051 *
052 * <p>Usage example: <pre>   {@code
053 *
054 *   MinMaxPriorityQueue<User> users = MinMaxPriorityQueue.orderedBy(userComparator)
055 *       .maximumSize(1000)
056 *       .create();}</pre>
057 *
058 * <p>As a {@link Queue} it functions exactly as a {@link PriorityQueue}: its
059 * head element -- the implicit target of the methods {@link #peek()}, {@link
060 * #poll()} and {@link #remove()} -- is defined as the <i>least</i> element in
061 * the queue according to the queue's comparator. But unlike a regular priority
062 * queue, the methods {@link #peekLast}, {@link #pollLast} and
063 * {@link #removeLast} are also provided, to act on the <i>greatest</i> element
064 * in the queue instead.
065 *
066 * <p>A min-max priority queue can be configured with a maximum size. If so,
067 * each time the size of the queue exceeds that value, the queue automatically
068 * removes its greatest element according to its comparator (which might be the
069 * element that was just added). This is different from conventional bounded
070 * queues, which either block or reject new elements when full.
071 *
072 * <p>This implementation is based on the
073 * <a href="http://portal.acm.org/citation.cfm?id=6621">min-max heap</a>
074 * developed by Atkinson, et al. Unlike many other double-ended priority queues,
075 * it stores elements in a single array, as compact as the traditional heap data
076 * structure used in {@link PriorityQueue}.
077 *
078 * <p>This class is not thread-safe, and does not accept null elements.
079 *
080 * <p><i>Performance notes:</i>
081 *
082 * <ul>
083 * <li>If you only access one end of the queue, and do use a maximum size,
084 *     this class will perform significantly worse than a {@code PriorityQueue}
085 *     with manual eviction above the maximum size.  In many cases
086 *     {@link Ordering#leastOf} may work for your use case with significantly
087 *     improved (and asymptotically superior) performance.
088 * <li>The retrieval operations {@link #peek}, {@link #peekFirst}, {@link
089 *     #peekLast}, {@link #element}, and {@link #size} are constant-time.
090 * <li>The enqueing and dequeing operations ({@link #offer}, {@link #add}, and
091 *     all the forms of {@link #poll} and {@link #remove()}) run in {@code
092 *     O(log n) time}.
093 * <li>The {@link #remove(Object)} and {@link #contains} operations require
094 *     linear ({@code O(n)}) time.
095 * <li>If you only access one end of the queue, and don't use a maximum size,
096 *     this class is functionally equivalent to {@link PriorityQueue}, but
097 *     significantly slower.
098 * </ul>
099 *
100 * @author Sverre Sundsdal
101 * @author Torbjorn Gannholm
102 * @since 8.0
103 */
104@Beta
105@GwtCompatible
106public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {
107
108  /**
109   * Creates a new min-max priority queue with default settings: natural order,
110   * no maximum size, no initial contents, and an initial expected size of 11.
111   */
112  public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create() {
113    return new Builder<Comparable>(Ordering.natural()).create();
114  }
115
116  /**
117   * Creates a new min-max priority queue using natural order, no maximum size,
118   * and initially containing the given elements.
119   */
120  public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create(
121      Iterable<? extends E> initialContents) {
122    return new Builder<E>(Ordering.<E>natural()).create(initialContents);
123  }
124
125  /**
126   * Creates and returns a new builder, configured to build {@code
127   * MinMaxPriorityQueue} instances that use {@code comparator} to determine the
128   * least and greatest elements.
129   */
130  public static <B> Builder<B> orderedBy(Comparator<B> comparator) {
131    return new Builder<B>(comparator);
132  }
133
134  /**
135   * Creates and returns a new builder, configured to build {@code
136   * MinMaxPriorityQueue} instances sized appropriately to hold {@code
137   * expectedSize} elements.
138   */
139  public static Builder<Comparable> expectedSize(int expectedSize) {
140    return new Builder<Comparable>(Ordering.natural()).expectedSize(expectedSize);
141  }
142
143  /**
144   * Creates and returns a new builder, configured to build {@code
145   * MinMaxPriorityQueue} instances that are limited to {@code maximumSize}
146   * elements. Each time a queue grows beyond this bound, it immediately
147   * removes its greatest element (according to its comparator), which might be
148   * the element that was just added.
149   */
150  public static Builder<Comparable> maximumSize(int maximumSize) {
151    return new Builder<Comparable>(Ordering.natural()).maximumSize(maximumSize);
152  }
153
154  /**
155   * The builder class used in creation of min-max priority queues. Instead of
156   * constructing one directly, use {@link
157   * MinMaxPriorityQueue#orderedBy(Comparator)}, {@link
158   * MinMaxPriorityQueue#expectedSize(int)} or {@link
159   * MinMaxPriorityQueue#maximumSize(int)}.
160   *
161   * @param <B> the upper bound on the eventual type that can be produced by
162   *     this builder (for example, a {@code Builder<Number>} can produce a
163   *     {@code Queue<Number>} or {@code Queue<Integer>} but not a {@code
164   *     Queue<Object>}).
165   * @since 8.0
166   */
167  @Beta
168  public static final class Builder<B> {
169    /*
170     * TODO(kevinb): when the dust settles, see if we still need this or can
171     * just default to DEFAULT_CAPACITY.
172     */
173    private static final int UNSET_EXPECTED_SIZE = -1;
174
175    private final Comparator<B> comparator;
176    private int expectedSize = UNSET_EXPECTED_SIZE;
177    private int maximumSize = Integer.MAX_VALUE;
178
179    private Builder(Comparator<B> comparator) {
180      this.comparator = checkNotNull(comparator);
181    }
182
183    /**
184     * Configures this builder to build min-max priority queues with an initial
185     * expected size of {@code expectedSize}.
186     */
187    @CanIgnoreReturnValue
188    public Builder<B> expectedSize(int expectedSize) {
189      checkArgument(expectedSize >= 0);
190      this.expectedSize = expectedSize;
191      return this;
192    }
193
194    /**
195     * Configures this builder to build {@code MinMaxPriorityQueue} instances
196     * that are limited to {@code maximumSize} elements. Each time a queue grows
197     * beyond this bound, it immediately removes its greatest element (according
198     * to its comparator), which might be the element that was just added.
199     */
200    @CanIgnoreReturnValue
201    public Builder<B> maximumSize(int maximumSize) {
202      checkArgument(maximumSize > 0);
203      this.maximumSize = maximumSize;
204      return this;
205    }
206
207    /**
208     * Builds a new min-max priority queue using the previously specified
209     * options, and having no initial contents.
210     */
211    public <T extends B> MinMaxPriorityQueue<T> create() {
212      return create(Collections.<T>emptySet());
213    }
214
215    /**
216     * Builds a new min-max priority queue using the previously specified
217     * options, and having the given initial elements.
218     */
219    public <T extends B> MinMaxPriorityQueue<T> create(Iterable<? extends T> initialContents) {
220      MinMaxPriorityQueue<T> queue =
221          new MinMaxPriorityQueue<T>(
222              this, initialQueueSize(expectedSize, maximumSize, initialContents));
223      for (T element : initialContents) {
224        queue.offer(element);
225      }
226      return queue;
227    }
228
229    @SuppressWarnings("unchecked") // safe "contravariant cast"
230    private <T extends B> Ordering<T> ordering() {
231      return Ordering.from((Comparator<T>) comparator);
232    }
233  }
234
235  private final Heap minHeap;
236  private final Heap maxHeap;
237  @VisibleForTesting final int maximumSize;
238  private Object[] queue;
239  private int size;
240  private int modCount;
241
242  private MinMaxPriorityQueue(Builder<? super E> builder, int queueSize) {
243    Ordering<E> ordering = builder.ordering();
244    this.minHeap = new Heap(ordering);
245    this.maxHeap = new Heap(ordering.reverse());
246    minHeap.otherHeap = maxHeap;
247    maxHeap.otherHeap = minHeap;
248
249    this.maximumSize = builder.maximumSize;
250    // TODO(kevinb): pad?
251    this.queue = new Object[queueSize];
252  }
253
254  @Override
255  public int size() {
256    return size;
257  }
258
259  /**
260   * Adds the given element to this queue. If this queue has a maximum size,
261   * after adding {@code element} the queue will automatically evict its
262   * greatest element (according to its comparator), which may be {@code
263   * element} itself.
264   *
265   * @return {@code true} always
266   */
267  @CanIgnoreReturnValue
268  @Override
269  public boolean add(E element) {
270    offer(element);
271    return true;
272  }
273
274  @CanIgnoreReturnValue
275  @Override
276  public boolean addAll(Collection<? extends E> newElements) {
277    boolean modified = false;
278    for (E element : newElements) {
279      offer(element);
280      modified = true;
281    }
282    return modified;
283  }
284
285  /**
286   * Adds the given element to this queue. If this queue has a maximum size,
287   * after adding {@code element} the queue will automatically evict its
288   * greatest element (according to its comparator), which may be {@code
289   * element} itself.
290   */
291  @CanIgnoreReturnValue
292  @Override
293  public boolean offer(E element) {
294    checkNotNull(element);
295    modCount++;
296    int insertIndex = size++;
297
298    growIfNeeded();
299
300    // Adds the element to the end of the heap and bubbles it up to the correct
301    // position.
302    heapForIndex(insertIndex).bubbleUp(insertIndex, element);
303    return size <= maximumSize || pollLast() != element;
304  }
305
306  @CanIgnoreReturnValue
307  @Override
308  public E poll() {
309    return isEmpty() ? null : removeAndGet(0);
310  }
311
312  @SuppressWarnings("unchecked") // we must carefully only allow Es to get in
313  E elementData(int index) {
314    return (E) queue[index];
315  }
316
317  @Override
318  public E peek() {
319    return isEmpty() ? null : elementData(0);
320  }
321
322  /**
323   * Returns the index of the max element.
324   */
325  private int getMaxElementIndex() {
326    switch (size) {
327      case 1:
328        return 0; // The lone element in the queue is the maximum.
329      case 2:
330        return 1; // The lone element in the maxHeap is the maximum.
331      default:
332        // The max element must sit on the first level of the maxHeap. It is
333        // actually the *lesser* of the two from the maxHeap's perspective.
334        return (maxHeap.compareElements(1, 2) <= 0) ? 1 : 2;
335    }
336  }
337
338  /**
339   * Removes and returns the least element of this queue, or returns {@code
340   * null} if the queue is empty.
341   */
342  @CanIgnoreReturnValue
343  public E pollFirst() {
344    return poll();
345  }
346
347  /**
348   * Removes and returns the least element of this queue.
349   *
350   * @throws NoSuchElementException if the queue is empty
351   */
352  @CanIgnoreReturnValue
353  public E removeFirst() {
354    return remove();
355  }
356
357  /**
358   * Retrieves, but does not remove, the least element of this queue, or returns
359   * {@code null} if the queue is empty.
360   */
361  public E peekFirst() {
362    return peek();
363  }
364
365  /**
366   * Removes and returns the greatest element of this queue, or returns {@code
367   * null} if the queue is empty.
368   */
369  @CanIgnoreReturnValue
370  public E pollLast() {
371    return isEmpty() ? null : removeAndGet(getMaxElementIndex());
372  }
373
374  /**
375   * Removes and returns the greatest element of this queue.
376   *
377   * @throws NoSuchElementException if the queue is empty
378   */
379  @CanIgnoreReturnValue
380  public E removeLast() {
381    if (isEmpty()) {
382      throw new NoSuchElementException();
383    }
384    return removeAndGet(getMaxElementIndex());
385  }
386
387  /**
388   * Retrieves, but does not remove, the greatest element of this queue, or
389   * returns {@code null} if the queue is empty.
390   */
391  public E peekLast() {
392    return isEmpty() ? null : elementData(getMaxElementIndex());
393  }
394
395  /**
396   * Removes the element at position {@code index}.
397   *
398   * <p>Normally this method leaves the elements at up to {@code index - 1},
399   * inclusive, untouched.  Under these circumstances, it returns {@code null}.
400   *
401   * <p>Occasionally, in order to maintain the heap invariant, it must swap a
402   * later element of the list with one before {@code index}. Under these
403   * circumstances it returns a pair of elements as a {@link MoveDesc}. The
404   * first one is the element that was previously at the end of the heap and is
405   * now at some position before {@code index}. The second element is the one
406   * that was swapped down to replace the element at {@code index}. This fact is
407   * used by iterator.remove so as to visit elements during a traversal once and
408   * only once.
409   */
410  @VisibleForTesting
411  @CanIgnoreReturnValue
412  MoveDesc<E> removeAt(int index) {
413    checkPositionIndex(index, size);
414    modCount++;
415    size--;
416    if (size == index) {
417      queue[size] = null;
418      return null;
419    }
420    E actualLastElement = elementData(size);
421    int lastElementAt = heapForIndex(size).getCorrectLastElement(actualLastElement);
422    E toTrickle = elementData(size);
423    queue[size] = null;
424    MoveDesc<E> changes = fillHole(index, toTrickle);
425    if (lastElementAt < index) {
426      // Last element is moved to before index, swapped with trickled element.
427      if (changes == null) {
428        // The trickled element is still after index.
429        return new MoveDesc<E>(actualLastElement, toTrickle);
430      } else {
431        // The trickled element is back before index, but the replaced element
432        // has now been moved after index.
433        return new MoveDesc<E>(actualLastElement, changes.replaced);
434      }
435    }
436    // Trickled element was after index to begin with, no adjustment needed.
437    return changes;
438  }
439
440  private MoveDesc<E> fillHole(int index, E toTrickle) {
441    Heap heap = heapForIndex(index);
442    // We consider elementData(index) a "hole", and we want to fill it
443    // with the last element of the heap, toTrickle.
444    // Since the last element of the heap is from the bottom level, we
445    // optimistically fill index position with elements from lower levels,
446    // moving the hole down. In most cases this reduces the number of
447    // comparisons with toTrickle, but in some cases we will need to bubble it
448    // all the way up again.
449    int vacated = heap.fillHoleAt(index);
450    // Try to see if toTrickle can be bubbled up min levels.
451    int bubbledTo = heap.bubbleUpAlternatingLevels(vacated, toTrickle);
452    if (bubbledTo == vacated) {
453      // Could not bubble toTrickle up min levels, try moving
454      // it from min level to max level (or max to min level) and bubble up
455      // there.
456      return heap.tryCrossOverAndBubbleUp(index, vacated, toTrickle);
457    } else {
458      return (bubbledTo < index) ? new MoveDesc<E>(toTrickle, elementData(index)) : null;
459    }
460  }
461
462  // Returned from removeAt() to iterator.remove()
463  static class MoveDesc<E> {
464    final E toTrickle;
465    final E replaced;
466
467    MoveDesc(E toTrickle, E replaced) {
468      this.toTrickle = toTrickle;
469      this.replaced = replaced;
470    }
471  }
472
473  /**
474   * Removes and returns the value at {@code index}.
475   */
476  private E removeAndGet(int index) {
477    E value = elementData(index);
478    removeAt(index);
479    return value;
480  }
481
482  private Heap heapForIndex(int i) {
483    return isEvenLevel(i) ? minHeap : maxHeap;
484  }
485
486  private static final int EVEN_POWERS_OF_TWO = 0x55555555;
487  private static final int ODD_POWERS_OF_TWO = 0xaaaaaaaa;
488
489  @VisibleForTesting
490  static boolean isEvenLevel(int index) {
491    int oneBased = ~~(index + 1); // for GWT
492    checkState(oneBased > 0, "negative index");
493    return (oneBased & EVEN_POWERS_OF_TWO) > (oneBased & ODD_POWERS_OF_TWO);
494  }
495
496  /**
497   * Returns {@code true} if the MinMax heap structure holds. This is only used
498   * in testing.
499   *
500   * TODO(kevinb): move to the test class?
501   */
502  @VisibleForTesting
503  boolean isIntact() {
504    for (int i = 1; i < size; i++) {
505      if (!heapForIndex(i).verifyIndex(i)) {
506        return false;
507      }
508    }
509    return true;
510  }
511
512  /**
513   * Each instance of MinMaxPriortyQueue encapsulates two instances of Heap:
514   * a min-heap and a max-heap. Conceptually, these might each have their own
515   * array for storage, but for efficiency's sake they are stored interleaved on
516   * alternate heap levels in the same array (MMPQ.queue).
517   */
518  @WeakOuter
519  private class Heap {
520    final Ordering<E> ordering;
521    @Weak Heap otherHeap;
522
523    Heap(Ordering<E> ordering) {
524      this.ordering = ordering;
525    }
526
527    int compareElements(int a, int b) {
528      return ordering.compare(elementData(a), elementData(b));
529    }
530
531    /**
532     * Tries to move {@code toTrickle} from a min to a max level and
533     * bubble up there. If it moved before {@code removeIndex} this method
534     * returns a pair as described in {@link #removeAt}.
535     */
536    MoveDesc<E> tryCrossOverAndBubbleUp(int removeIndex, int vacated, E toTrickle) {
537      int crossOver = crossOver(vacated, toTrickle);
538      if (crossOver == vacated) {
539        return null;
540      }
541      // Successfully crossed over from min to max.
542      // Bubble up max levels.
543      E parent;
544      // If toTrickle is moved up to a parent of removeIndex, the parent is
545      // placed in removeIndex position. We must return that to the iterator so
546      // that it knows to skip it.
547      if (crossOver < removeIndex) {
548        // We crossed over to the parent level in crossOver, so the parent
549        // has already been moved.
550        parent = elementData(removeIndex);
551      } else {
552        parent = elementData(getParentIndex(removeIndex));
553      }
554      // bubble it up the opposite heap
555      if (otherHeap.bubbleUpAlternatingLevels(crossOver, toTrickle) < removeIndex) {
556        return new MoveDesc<E>(toTrickle, parent);
557      } else {
558        return null;
559      }
560    }
561
562    /**
563     * Bubbles a value from {@code index} up the appropriate heap if required.
564     */
565    void bubbleUp(int index, E x) {
566      int crossOver = crossOverUp(index, x);
567
568      Heap heap;
569      if (crossOver == index) {
570        heap = this;
571      } else {
572        index = crossOver;
573        heap = otherHeap;
574      }
575      heap.bubbleUpAlternatingLevels(index, x);
576    }
577
578    /**
579     * Bubbles a value from {@code index} up the levels of this heap, and
580     * returns the index the element ended up at.
581     */
582    @CanIgnoreReturnValue
583    int bubbleUpAlternatingLevels(int index, E x) {
584      while (index > 2) {
585        int grandParentIndex = getGrandparentIndex(index);
586        E e = elementData(grandParentIndex);
587        if (ordering.compare(e, x) <= 0) {
588          break;
589        }
590        queue[index] = e;
591        index = grandParentIndex;
592      }
593      queue[index] = x;
594      return index;
595    }
596
597    /**
598     * Returns the index of minimum value between {@code index} and
599     * {@code index + len}, or {@code -1} if {@code index} is greater than
600     * {@code size}.
601     */
602    int findMin(int index, int len) {
603      if (index >= size) {
604        return -1;
605      }
606      checkState(index > 0);
607      int limit = Math.min(index, size - len) + len;
608      int minIndex = index;
609      for (int i = index + 1; i < limit; i++) {
610        if (compareElements(i, minIndex) < 0) {
611          minIndex = i;
612        }
613      }
614      return minIndex;
615    }
616
617    /**
618     * Returns the minimum child or {@code -1} if no child exists.
619     */
620    int findMinChild(int index) {
621      return findMin(getLeftChildIndex(index), 2);
622    }
623
624    /**
625     * Returns the minimum grand child or -1 if no grand child exists.
626     */
627    int findMinGrandChild(int index) {
628      int leftChildIndex = getLeftChildIndex(index);
629      if (leftChildIndex < 0) {
630        return -1;
631      }
632      return findMin(getLeftChildIndex(leftChildIndex), 4);
633    }
634
635    /**
636     * Moves an element one level up from a min level to a max level
637     * (or vice versa).
638     * Returns the new position of the element.
639     */
640    int crossOverUp(int index, E x) {
641      if (index == 0) {
642        queue[0] = x;
643        return 0;
644      }
645      int parentIndex = getParentIndex(index);
646      E parentElement = elementData(parentIndex);
647      if (parentIndex != 0) {
648        // This is a guard for the case of the childless uncle.
649        // Since the end of the array is actually the middle of the heap,
650        // a smaller childless uncle can become a child of x when we
651        // bubble up alternate levels, violating the invariant.
652        int grandparentIndex = getParentIndex(parentIndex);
653        int uncleIndex = getRightChildIndex(grandparentIndex);
654        if (uncleIndex != parentIndex && getLeftChildIndex(uncleIndex) >= size) {
655          E uncleElement = elementData(uncleIndex);
656          if (ordering.compare(uncleElement, parentElement) < 0) {
657            parentIndex = uncleIndex;
658            parentElement = uncleElement;
659          }
660        }
661      }
662      if (ordering.compare(parentElement, x) < 0) {
663        queue[index] = parentElement;
664        queue[parentIndex] = x;
665        return parentIndex;
666      }
667      queue[index] = x;
668      return index;
669    }
670
671    /**
672     * Returns the conceptually correct last element of the heap.
673     *
674     * <p>Since the last element of the array is actually in the
675     * middle of the sorted structure, a childless uncle node could be
676     * smaller, which would corrupt the invariant if this element
677     * becomes the new parent of the uncle. In that case, we first
678     * switch the last element with its uncle, before returning.
679     */
680    int getCorrectLastElement(E actualLastElement) {
681      int parentIndex = getParentIndex(size);
682      if (parentIndex != 0) {
683        int grandparentIndex = getParentIndex(parentIndex);
684        int uncleIndex = getRightChildIndex(grandparentIndex);
685        if (uncleIndex != parentIndex && getLeftChildIndex(uncleIndex) >= size) {
686          E uncleElement = elementData(uncleIndex);
687          if (ordering.compare(uncleElement, actualLastElement) < 0) {
688            queue[uncleIndex] = actualLastElement;
689            queue[size] = uncleElement;
690            return uncleIndex;
691          }
692        }
693      }
694      return size;
695    }
696
697    /**
698     * Crosses an element over to the opposite heap by moving it one level down
699     * (or up if there are no elements below it).
700     *
701     * Returns the new position of the element.
702     */
703    int crossOver(int index, E x) {
704      int minChildIndex = findMinChild(index);
705      // TODO(kevinb): split the && into two if's and move crossOverUp so it's
706      // only called when there's no child.
707      if ((minChildIndex > 0) && (ordering.compare(elementData(minChildIndex), x) < 0)) {
708        queue[index] = elementData(minChildIndex);
709        queue[minChildIndex] = x;
710        return minChildIndex;
711      }
712      return crossOverUp(index, x);
713    }
714
715    /**
716     * Fills the hole at {@code index} by moving in the least of its
717     * grandchildren to this position, then recursively filling the new hole
718     * created.
719     *
720     * @return the position of the new hole (where the lowest grandchild moved
721     *     from, that had no grandchild to replace it)
722     */
723    int fillHoleAt(int index) {
724      int minGrandchildIndex;
725      while ((minGrandchildIndex = findMinGrandChild(index)) > 0) {
726        queue[index] = elementData(minGrandchildIndex);
727        index = minGrandchildIndex;
728      }
729      return index;
730    }
731
732    private boolean verifyIndex(int i) {
733      if ((getLeftChildIndex(i) < size) && (compareElements(i, getLeftChildIndex(i)) > 0)) {
734        return false;
735      }
736      if ((getRightChildIndex(i) < size) && (compareElements(i, getRightChildIndex(i)) > 0)) {
737        return false;
738      }
739      if ((i > 0) && (compareElements(i, getParentIndex(i)) > 0)) {
740        return false;
741      }
742      if ((i > 2) && (compareElements(getGrandparentIndex(i), i) > 0)) {
743        return false;
744      }
745      return true;
746    }
747
748    // These would be static if inner classes could have static members.
749
750    private int getLeftChildIndex(int i) {
751      return i * 2 + 1;
752    }
753
754    private int getRightChildIndex(int i) {
755      return i * 2 + 2;
756    }
757
758    private int getParentIndex(int i) {
759      return (i - 1) / 2;
760    }
761
762    private int getGrandparentIndex(int i) {
763      return getParentIndex(getParentIndex(i)); // (i - 3) / 4
764    }
765  }
766
767  /**
768   * Iterates the elements of the queue in no particular order.
769   *
770   * If the underlying queue is modified during iteration an exception will be
771   * thrown.
772   */
773  private class QueueIterator implements Iterator<E> {
774    private int cursor = -1;
775    private int expectedModCount = modCount;
776    private Queue<E> forgetMeNot;
777    private List<E> skipMe;
778    private E lastFromForgetMeNot;
779    private boolean canRemove;
780
781    @Override
782    public boolean hasNext() {
783      checkModCount();
784      return (nextNotInSkipMe(cursor + 1) < size())
785          || ((forgetMeNot != null) && !forgetMeNot.isEmpty());
786    }
787
788    @Override
789    public E next() {
790      checkModCount();
791      int tempCursor = nextNotInSkipMe(cursor + 1);
792      if (tempCursor < size()) {
793        cursor = tempCursor;
794        canRemove = true;
795        return elementData(cursor);
796      } else if (forgetMeNot != null) {
797        cursor = size();
798        lastFromForgetMeNot = forgetMeNot.poll();
799        if (lastFromForgetMeNot != null) {
800          canRemove = true;
801          return lastFromForgetMeNot;
802        }
803      }
804      throw new NoSuchElementException("iterator moved past last element in queue.");
805    }
806
807    @Override
808    public void remove() {
809      checkRemove(canRemove);
810      checkModCount();
811      canRemove = false;
812      expectedModCount++;
813      if (cursor < size()) {
814        MoveDesc<E> moved = removeAt(cursor);
815        if (moved != null) {
816          if (forgetMeNot == null) {
817            forgetMeNot = new ArrayDeque<E>();
818            skipMe = new ArrayList<E>(3);
819          }
820          forgetMeNot.add(moved.toTrickle);
821          skipMe.add(moved.replaced);
822        }
823        cursor--;
824      } else { // we must have set lastFromForgetMeNot in next()
825        checkState(removeExact(lastFromForgetMeNot));
826        lastFromForgetMeNot = null;
827      }
828    }
829
830    // Finds only this exact instance, not others that are equals()
831    private boolean containsExact(Iterable<E> elements, E target) {
832      for (E element : elements) {
833        if (element == target) {
834          return true;
835        }
836      }
837      return false;
838    }
839
840    // Removes only this exact instance, not others that are equals()
841    boolean removeExact(Object target) {
842      for (int i = 0; i < size; i++) {
843        if (queue[i] == target) {
844          removeAt(i);
845          return true;
846        }
847      }
848      return false;
849    }
850
851    void checkModCount() {
852      if (modCount != expectedModCount) {
853        throw new ConcurrentModificationException();
854      }
855    }
856
857    /**
858     * Returns the index of the first element after {@code c} that is not in
859     * {@code skipMe} and returns {@code size()} if there is no such element.
860     */
861    private int nextNotInSkipMe(int c) {
862      if (skipMe != null) {
863        while (c < size() && containsExact(skipMe, elementData(c))) {
864          c++;
865        }
866      }
867      return c;
868    }
869  }
870
871  /**
872   * Returns an iterator over the elements contained in this collection,
873   * <i>in no particular order</i>.
874   *
875   * <p>The iterator is <i>fail-fast</i>: If the MinMaxPriorityQueue is modified
876   * at any time after the iterator is created, in any way except through the
877   * iterator's own remove method, the iterator will generally throw a
878   * {@link ConcurrentModificationException}. Thus, in the face of concurrent
879   * modification, the iterator fails quickly and cleanly, rather than risking
880   * arbitrary, non-deterministic behavior at an undetermined time in the
881   * future.
882   *
883   * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
884   * as it is, generally speaking, impossible to make any hard guarantees in the
885   * presence of unsynchronized concurrent modification.  Fail-fast iterators
886   * throw {@code ConcurrentModificationException} on a best-effort basis.
887   * Therefore, it would be wrong to write a program that depended on this
888   * exception for its correctness: <i>the fail-fast behavior of iterators
889   * should be used only to detect bugs.</i>
890   *
891   * @return an iterator over the elements contained in this collection
892   */
893  @Override
894  public Iterator<E> iterator() {
895    return new QueueIterator();
896  }
897
898  @Override
899  public void clear() {
900    for (int i = 0; i < size; i++) {
901      queue[i] = null;
902    }
903    size = 0;
904  }
905
906  @Override
907  public Object[] toArray() {
908    Object[] copyTo = new Object[size];
909    System.arraycopy(queue, 0, copyTo, 0, size);
910    return copyTo;
911  }
912
913  /**
914   * Returns the comparator used to order the elements in this queue. Obeys the
915   * general contract of {@link PriorityQueue#comparator}, but returns {@link
916   * Ordering#natural} instead of {@code null} to indicate natural ordering.
917   */
918  public Comparator<? super E> comparator() {
919    return minHeap.ordering;
920  }
921
922  @VisibleForTesting
923  int capacity() {
924    return queue.length;
925  }
926
927  // Size/capacity-related methods
928
929  private static final int DEFAULT_CAPACITY = 11;
930
931  @VisibleForTesting
932  static int initialQueueSize(
933      int configuredExpectedSize, int maximumSize, Iterable<?> initialContents) {
934    // Start with what they said, if they said it, otherwise DEFAULT_CAPACITY
935    int result =
936        (configuredExpectedSize == Builder.UNSET_EXPECTED_SIZE)
937            ? DEFAULT_CAPACITY
938            : configuredExpectedSize;
939
940    // Enlarge to contain initial contents
941    if (initialContents instanceof Collection) {
942      int initialSize = ((Collection<?>) initialContents).size();
943      result = Math.max(result, initialSize);
944    }
945
946    // Now cap it at maxSize + 1
947    return capAtMaximumSize(result, maximumSize);
948  }
949
950  private void growIfNeeded() {
951    if (size > queue.length) {
952      int newCapacity = calculateNewCapacity();
953      Object[] newQueue = new Object[newCapacity];
954      System.arraycopy(queue, 0, newQueue, 0, queue.length);
955      queue = newQueue;
956    }
957  }
958
959  /** Returns ~2x the old capacity if small; ~1.5x otherwise. */
960  private int calculateNewCapacity() {
961    int oldCapacity = queue.length;
962    int newCapacity =
963        (oldCapacity < 64)
964            ? (oldCapacity + 1) * 2
965            : IntMath.checkedMultiply(oldCapacity / 2, 3);
966    return capAtMaximumSize(newCapacity, maximumSize);
967  }
968
969  /** There's no reason for the queueSize to ever be more than maxSize + 1 */
970  private static int capAtMaximumSize(int queueSize, int maximumSize) {
971    return Math.min(queueSize - 1, maximumSize) + 1; // don't overflow
972  }
973}