📄 priorityqueue.java
字号:
/*
* %W% %E%
*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package edu.emory.mathcs.backport.java.util;
import java.util.*;
/**
* An unbounded priority {@linkplain Queue queue} based on a priority
* heap. This queue orders elements according to an order specified
* at construction time, which is specified either according to their
* <i>natural order</i> (see {@link Comparable}), or according to a
* {@link java.util.Comparator}, depending on which constructor is
* used. A priority queue does not permit <tt>null</tt> elements.
* A priority queue relying on natural ordering also does not
* permit insertion of non-comparable objects (doing so may result
* in <tt>ClassCastException</tt>).
*
* <p>The <em>head</em> of this queue is the <em>least</em> element
* with respect to the specified ordering. If multiple elements are
* tied for least value, the head is one of those elements -- ties are
* broken arbitrarily. The queue retrieval operations <tt>poll</tt>,
* <tt>remove</tt>, <tt>peek</tt>, and <tt>element</tt> access the
* element at the head of the queue.
*
* <p>A priority queue is unbounded, but has an internal
* <i>capacity</i> governing the size of an array used to store the
* elements on the queue. It is always at least as large as the queue
* size. As elements are added to a priority queue, its capacity
* grows automatically. The details of the growth policy are not
* specified.
*
* <p>This class and its iterator implement all of the
* <em>optional</em> methods of the {@link Collection} and {@link
* Iterator} interfaces.
* The
* Iterator provided in method {@link #iterator()} is <em>not</em>
* guaranteed to traverse the elements of the PriorityQueue in any
* particular order. If you need ordered traversal, consider using
* <tt>Arrays.sort(pq.toArray())</tt>.
*
* <p> <strong>Note that this implementation is not synchronized.</strong>
* Multiple threads should not access a <tt>PriorityQueue</tt>
* instance concurrently if any of the threads modifies the list
* structurally. Instead, use the thread-safe {@link
* edu.emory.mathcs.backport.java.util.concurrent.PriorityBlockingQueue} class.
*
*
* <p>Implementation note: this implementation provides O(log(n)) time
* for the insertion methods (<tt>offer</tt>, <tt>poll</tt>,
* <tt>remove()</tt> and <tt>add</tt>) methods; linear time for the
* <tt>remove(Object)</tt> and <tt>contains(Object)</tt> methods; and
* constant time for the retrieval methods (<tt>peek</tt>,
* <tt>element</tt>, and <tt>size</tt>).
*
* <p>This class is a member of the
* <a href="{@docRoot}/../guide/collections/index.html">
* Java Collections Framework</a>.
* @since 1.5
* @version %I%, %G%
* @author Josh Bloch
*/
public class PriorityQueue extends AbstractQueue
implements java.io.Serializable {
private static final long serialVersionUID = -7720805057305804111L;
private static final int DEFAULT_INITIAL_CAPACITY = 11;
/**
* Priority queue represented as a balanced binary heap: the two children
* of queue[n] are queue[2*n] and queue[2*n + 1]. The priority queue is
* ordered by comparator, or by the elements' natural ordering, if
* comparator is null: For each node n in the heap and each descendant d
* of n, n <= d.
*
* The element with the lowest value is in queue[1], assuming the queue is
* nonempty. (A one-based array is used in preference to the traditional
* zero-based array to simplify parent and child calculations.)
*
* queue.length must be >= 2, even if size == 0.
*/
private transient Object[] queue;
/**
* The number of elements in the priority queue.
*/
private int size = 0;
/**
* The comparator, or null if priority queue uses elements'
* natural ordering.
*/
private final Comparator comparator;
/**
* The number of times this priority queue has been
* <i>structurally modified</i>. See AbstractList for gory details.
*/
private transient int modCount = 0;
/**
* Creates a <tt>PriorityQueue</tt> with the default initial capacity
* (11) that orders its elements according to their natural
* ordering (using <tt>Comparable</tt>).
*/
public PriorityQueue() {
this(DEFAULT_INITIAL_CAPACITY, null);
}
/**
* Creates a <tt>PriorityQueue</tt> with the specified initial capacity
* that orders its elements according to their natural ordering
* (using <tt>Comparable</tt>).
*
* @param initialCapacity the initial capacity for this priority queue.
* @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
* than 1
*/
public PriorityQueue(int initialCapacity) {
this(initialCapacity, null);
}
/**
* Creates a <tt>PriorityQueue</tt> with the specified initial capacity
* that orders its elements according to the specified comparator.
*
* @param initialCapacity the initial capacity for this priority queue.
* @param comparator the comparator used to order this priority queue.
* If <tt>null</tt> then the order depends on the elements' natural
* ordering.
* @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
* than 1
*/
public PriorityQueue(int initialCapacity,
Comparator comparator) {
if (initialCapacity < 1)
throw new IllegalArgumentException();
this.queue = new Object[initialCapacity + 1];
this.comparator = comparator;
}
/**
* Common code to initialize underlying queue array across
* constructors below.
*/
private void initializeArray(Collection c) {
int sz = c.size();
int initialCapacity = (int)Math.min((sz * 110L) / 100,
Integer.MAX_VALUE - 1);
if (initialCapacity < 1)
initialCapacity = 1;
this.queue = new Object[initialCapacity + 1];
}
/**
* Initially fill elements of the queue array under the
* knowledge that it is sorted or is another PQ, in which
* case we can just place the elements in the order presented.
*/
private void fillFromSorted(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); )
queue[++size] = i.next();
}
/**
* Initially fill elements of the queue array that is not to our knowledge
* sorted, so we must rearrange the elements to guarantee the heap
* invariant.
*/
private void fillFromUnsorted(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); )
queue[++size] = i.next();
heapify();
}
/**
* Creates a <tt>PriorityQueue</tt> containing the elements in the
* specified collection. The priority queue has an initial
* capacity of 110% of the size of the specified collection or 1
* if the collection is empty. If the specified collection is an
* instance of a {@link java.util.SortedSet} or is another
* <tt>PriorityQueue</tt>, the priority queue will be sorted
* according to the same comparator, or according to its elements'
* natural order if the collection is sorted according to its
* elements' natural order. Otherwise, the priority queue is
* ordered according to its elements' natural order.
*
* @param c the collection whose elements are to be placed
* into this priority queue.
* @throws ClassCastException if elements of the specified collection
* cannot be compared to one another according to the priority
* queue's ordering.
* @throws NullPointerException if <tt>c</tt> or any element within it
* is <tt>null</tt>
*/
public PriorityQueue(Collection c) {
initializeArray(c);
if (c instanceof SortedSet) {
SortedSet s = (SortedSet)c;
comparator = (Comparator)s.comparator();
fillFromSorted(s);
} else if (c instanceof PriorityQueue) {
PriorityQueue s = (PriorityQueue) c;
comparator = (Comparator)s.comparator();
fillFromSorted(s);
} else {
comparator = null;
fillFromUnsorted(c);
}
}
/**
* Creates a <tt>PriorityQueue</tt> containing the elements in the
* specified collection. The priority queue has an initial
* capacity of 110% of the size of the specified collection or 1
* if the collection is empty. This priority queue will be sorted
* according to the same comparator as the given collection, or
* according to its elements' natural order if the collection is
* sorted according to its elements' natural order.
*
* @param c the collection whose elements are to be placed
* into this priority queue.
* @throws ClassCastException if elements of the specified collection
* cannot be compared to one another according to the priority
* queue's ordering.
* @throws NullPointerException if <tt>c</tt> or any element within it
* is <tt>null</tt>
*/
public PriorityQueue(PriorityQueue c) {
initializeArray(c);
comparator = (Comparator)c.comparator();
fillFromSorted(c);
}
/**
* Creates a <tt>PriorityQueue</tt> containing the elements in the
* specified collection. The priority queue has an initial
* capacity of 110% of the size of the specified collection or 1
* if the collection is empty. This priority queue will be sorted
* according to the same comparator as the given collection, or
* according to its elements' natural order if the collection is
* sorted according to its elements' natural order.
*
* @param c the collection whose elements are to be placed
* into this priority queue.
* @throws ClassCastException if elements of the specified collection
* cannot be compared to one another according to the priority
* queue's ordering.
* @throws NullPointerException if <tt>c</tt> or any element within it
* is <tt>null</tt>
*/
public PriorityQueue(SortedSet c) {
initializeArray(c);
comparator = (Comparator)c.comparator();
fillFromSorted(c);
}
/**
* Resize array, if necessary, to be able to hold given index
*/
private void grow(int index) {
int newlen = queue.length;
if (index < newlen) // don't need to grow
return;
if (index == Integer.MAX_VALUE)
throw new OutOfMemoryError();
while (newlen <= index) {
if (newlen >= Integer.MAX_VALUE / 2) // avoid overflow
newlen = Integer.MAX_VALUE;
else
newlen <<= 2;
}
Object[] newQueue = new Object[newlen];
System.arraycopy(queue, 0, newQueue, 0, queue.length);
queue = newQueue;
}
/**
* Inserts the specified element into this priority queue.
*
* @return <tt>true</tt>
* @throws ClassCastException if the specified element cannot be compared
* with elements currently in the priority queue according
* to the priority queue's ordering.
* @throws NullPointerException if the specified element is <tt>null</tt>.
*/
public boolean offer(Object o) {
if (o == null)
throw new NullPointerException();
modCount++;
++size;
// Grow backing store if necessary
if (size >= queue.length)
grow(size);
queue[size] = o;
fixUp(size);
return true;
}
public Object peek() {
if (size == 0)
return null;
return (Object) queue[1];
}
// Collection Methods - the first two override to update docs
/**
* Adds the specified element to this queue.
* @return <tt>true</tt> (as per the general contract of
* <tt>Collection.add</tt>).
*
* @throws NullPointerException if the specified element is <tt>null</tt>.
* @throws ClassCastException if the specified element cannot be compared
* with elements currently in the priority queue according
* to the priority queue's ordering.
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -