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