public class MinPQ<Key> extends java.lang.Object implements java.lang.Iterable<Key>
This implementation uses a binary heap. The insert and delete-the-minimum operations take logarithmic amortized time. The min, size, and is-empty operations take constant time. Construction takes time proportional to the specified capacity or the number of items used to initialize the data structure.
For additional documentation, see Section 2.4 of Algorithms, 4th Edition, by Robert Sedgewick and Kevin Wayne.
Constructor and Description |
---|
MinPQ()
Initializes an empty priority queue.
|
MinPQ(java.util.Comparator<Key> comparator)
Initializes an empty priority queue using the given comparator.
|
MinPQ(int initCapacity)
Initializes an empty priority queue with the given initial capacity.
|
MinPQ(int initCapacity,
java.util.Comparator<Key> comparator)
Initializes an empty priority queue with the given initial capacity,
using the given comparator.
|
MinPQ(Key[] keys)
Initializes a priority queue from the array of keys.
|
Modifier and Type | Method and Description |
---|---|
Key |
delMin()
Removes and returns a smallest key on the priority queue.
|
void |
insert(Key x)
Adds a new key to the priority queue.
|
boolean |
isEmpty()
Is the priority queue empty?
|
java.util.Iterator<Key> |
iterator()
Returns an iterator that iterates over the keys on the priority queue
in ascending order.
|
static void |
main(java.lang.String[] args)
Unit tests the MinPQ data type.
|
Key |
min()
Returns a smallest key on the priority queue.
|
int |
size()
Returns the number of keys on the priority queue.
|
public MinPQ(int initCapacity)
initCapacity
- the initial capacity of the priority queuepublic MinPQ()
public MinPQ(int initCapacity, java.util.Comparator<Key> comparator)
initCapacity
- the initial capacity of the priority queuecomparator
- the order to use when comparing keyspublic MinPQ(java.util.Comparator<Key> comparator)
comparator
- the order to use when comparing keyspublic MinPQ(Key[] keys)
keys
- the array of keyspublic boolean isEmpty()
public int size()
public Key min()
java.util.NoSuchElementException
- if priority queue is emptypublic void insert(Key x)
x
- the key to add to the priority queuepublic Key delMin()
java.util.NoSuchElementException
- if the priority queue is emptypublic java.util.Iterator<Key> iterator()
iterator
in interface java.lang.Iterable<Key>
public static void main(java.lang.String[] args)