命题Q。对于一个含有N个元素的基于堆叠优先队列,插入元素操作只需要不超过(lgN + 1)次比较,删除最大元素的操作需要不超过2lgN次比较。
证明。由命题P可知,两种操作都需要在根节点和堆底之间移动元素,而路径的长度不超过lgN。对于路径上的每个节点,删除最大元素需要两次比比较(除了堆底元素),一次用来找出较大的子节点,一次用来确定该子节点是否需要上浮。
对于需要大量混杂的插入和删除最大元素操作的典型应用来说,命题Q意味着一个重要的性能突破(详见优先队列增长数量级表)。使用有序或是无序数组的优先队列的初级实现总是需要线性时间来完成其中一种操作,但基于堆底实现则能够抱枕在对数时间内完成他们。这种差别使得我们能够解决以前无法解决的问题。
2.4.4.3 多叉堆
基于用数组表示的完全三叉树构造堆并修改相应的代码并不困难。对于数组中1 至N 的N个元素,位置k的结点大于等于位于3k - 1、3k和3k + 1的结点,小于等于位于[(k + 1) / 3 (d)]的结点。甚至对于给定的d,将其修改为任意的d叉树也并不困难。我们需要在树高(logaN)和在每个节点的d个子节点找到最大者的代价之间找到折中,这取决于实现的细节以及不同操作的预期相对频繁程度。堆上的优先队列操作如右图。
2.4.4.4 调整数组大小
我们可以添加一个没有参数的构造函数,在insert()中添加将数组长度加倍的代码,在delMax()中添加将数组长度减半的代码,就像栈那样。这样,算法的用例就无需管组各种队列大小的限制。当有限队列的数组大小可以跳帧、队列长度可以是任意值时,命题Q指出的对数时间复杂度上限就只是针对一般性的队列长度N而言了。
2.4.4.5 元素的不可变性
有限队列存储了用例创建的对象,但同时假设用例代码不会改变他们(改变他们就可能打破堆的有序性)。我们可以将这个假设为强制条件,但程序员通常不会这么做,因为增加代码的复杂性会降低性能。
2.4.4.6 索引优先队列
在很多应用中,允许用例引用已经进入有限队列中的元素是有必要的。做到这一点的一种简单方法是用例已经有了总量为N的多个元素,而且可能还同时使用了多个(平行)数组(Parallel Array)来存储这些元素的信息。此时,其他无关的用例代码可能已经在使用一个整数索引来引用这些元素了。这些考虑引导我们设计了下表。
理解这种数据结构的一个较好方法是将它看成一个能够快速访问其中最小元素的数组。事实上它还要更好——它能够快速访问数组的一个特定子集中的最小元素(指所有被插入的元素)。换句话说,可以将名为pq的IndexMinPQ优先队列看做数组pq[0..N - 1]中的一部分元素的代表。将pq.insert(k, item)看做将k加入这个子集并使pq[k] = item, pq.change(k, item)则代表令pq[k] = item。这两种操作没有改变其他操作所依赖的数据结构,其中最重要的就是delMin()(删除最小元素并返回它的索引)和change()(改变数据结构中的某个元素的索引——即pq[i] = item)。这些操作在许多应用中都很重要并且依赖于对元素的引用(索引)。一般来说,当堆发生变化时,我们会用下沉(元素减小时)或上浮(元素变大时)操作来恢复堆的有序性。在这些操作中,我们可以用索引查找元素。能够定位堆中的任意元素也使我们能够在API中加入一个delete()操作。
命题Q(续)。在一个大小为N的索引优先队列中,插入元素(insert)、改变优先级(change)、删除(delete)和删除最大小元素(remove the minimum)操作所需的比较次数和logN成正比(如后表)
证明。已知堆中所有路径最长即为~lgN,从代码中很容易得到这个结论。
操作 | 比较次数的增长数量级 |
insert() | logN |
change() | logN |
contains() | 1 |
delete() | logN |
min() | 1 |
minIndex() | 1 |
delMin |
logN |
这段讨论针对的是找好粗最小元素的队列;以下是《alg4》书中实现的一个找出最大元素的版本IndexMaxPQ。
import java.util.Iterator;
import java.util.NoSuchElementException; /**
* The <tt>IndexMaxPQ</tt> class represents an indexed priority queue of generic keys.
* It supports the usual <em>insert</em> and <em>delete-the-maximum</em>
* operations, along with <em>delete</em> and <em>change-the-key</em>
* methods. In order to let the client refer to items on the priority queue,
* an integer between 0 and NMAX-1 is associated with each key—the client
* uses this integer to specify which key to delete or change.
* It also supports methods for peeking at a maximum key,
* testing if the priority queue is empty, and iterating through
* the keys.
* <p>
* This implementation uses a binary heap along with an array to associate
* keys with integers in the given range.
* The <em>insert</em>, <em>delete-the-maximum</em>, <em>delete</em>,
* <em>change-key</em>, <em>decrease-key</em>, and <em>increase-key</em>
* operations take logarithmic time.
* The <em>is-empty</em>, <em>size</em>, <em>max-index</em>, <em>max-key</em>, and <em>key-of</em>
* operations take constant time.
* Construction takes time proportional to the specified capacity.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/24pq">Section 2.4</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class IndexMaxPQ<Key extends Comparable<Key>> implements Iterable<Integer> {
private int N; // number of elements on PQ
private int[] pq; // binary heap using 1-based indexing
private int[] qp; // inverse of pq - qp[pq[i]] = pq[qp[i]] = i
private Key[] keys; // keys[i] = priority of i /**
* Initializes an empty indexed priority queue with indices between 0 and NMAX-1.
* @param NMAX the keys on the priority queue are index from 0 to NMAX-1
* @throws java.lang.IllegalArgumentException if NMAX < 0
*/
public IndexMaxPQ(int NMAX) {
keys = (Key[]) new Comparable[NMAX + 1]; // make this of length NMAX??
pq = new int[NMAX + 1];
qp = new int[NMAX + 1]; // make this of length NMAX??
for (int i = 0; i <= NMAX; i++) qp[i] = -1;
} /**
* Is the priority queue empty?
* @return true if the priority queue is empty; false otherwise
*/
public boolean isEmpty() { return N == 0; } /**
* Is i an index on the priority queue?
* @param i an index
* @throws java.lang.IndexOutOfBoundsException unless (0 ≤ i < NMAX)
*/
public boolean contains(int i) {
return qp[i] != -1;
} /**
* Returns the number of keys on the priority queue.
* @return the number of keys on the priority queue
*/
public int size() {
return N;
} /**
* Associate key with index i.
* @param i an index
* @param key the key to associate with index i
* @throws java.lang.IndexOutOfBoundsException unless 0 ≤ i < NMAX
* @throws java.util.IllegalArgumentException if there already is an item associated with index i
*/
public void insert(int i, Key key) {
if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue");
N++;
qp[i] = N;
pq[N] = i;
keys[i] = key;
swim(N);
} /**
* Returns an index associated with a maximum key.
* @return an index associated with a maximum key
* @throws java.util.NoSuchElementException if priority queue is empty
*/
public int maxIndex() {
if (N == 0) throw new NoSuchElementException("Priority queue underflow");
return pq[1];
} /**
* Return a maximum key.
* @return a maximum key
* @throws java.util.NoSuchElementException if priority queue is empty
*/
public Key maxKey() {
if (N == 0) throw new NoSuchElementException("Priority queue underflow");
return keys[pq[1]];
} /**
* Removes a maximum key and returns its associated index.
* @return an index associated with a maximum key
* @throws java.util.NoSuchElementException if priority queue is empty
*/
public int delMax() {
if (N == 0) throw new NoSuchElementException("Priority queue underflow");
int min = pq[1];
exch(1, N--);
sink(1);
qp[min] = -1; // delete
keys[pq[N+1]] = null; // to help with garbage collection
pq[N+1] = -1; // not needed
return min;
} /**
* Returns the key associated with index i.
* @param i the index of the key to return
* @return the key associated with index i
* @throws java.lang.IndexOutOfBoundsException unless 0 ≤ i < NMAX
* @throws java.util.NoSuchElementException no key is associated with index i
*/
public Key keyOf(int i) {
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
else return keys[i];
} /**
* Change the key associated with index i to the specified value.
* @param i the index of the key to change
* @param key change the key assocated with index i to this key
* @throws java.lang.IndexOutOfBoundsException unless 0 ≤ i < NMAX
* @deprecated Replaced by changeKey()
*/
@Deprecated public void change(int i, Key key) {
changeKey(i, key);
} /**
* Change the key associated with index i to the specified value.
* @param i the index of the key to change
* @param key change the key assocated with index i to this key
* @throws java.lang.IndexOutOfBoundsException unless 0 ≤ i < NMAX
*/
public void changeKey(int i, Key key) {
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
keys[i] = key;
swim(qp[i]);
sink(qp[i]);
} /**
* Increase the key associated with index i to the specified value.
* @param i the index of the key to increase
* @param key increase the key assocated with index i to this key
* @throws java.lang.IndexOutOfBoundsException unless 0 ≤ i < NMAX
* @throws java.lang.IllegalArgumentException if key ≤ key associated with index i
* @throws java.util.NoSuchElementException no key is associated with index i
*/
public void increaseKey(int i, Key key) {
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
if (keys[i].compareTo(key) >= 0) throw new IllegalArgumentException("Calling increaseKey() with given argument would not strictly increase the key"); keys[i] = key;
swim(qp[i]);
} /**
* Decrease the key associated with index i to the specified value.
* @param i the index of the key to decrease
* @param key decrease the key assocated with index i to this key
* @throws java.lang.IndexOutOfBoundsException unless 0 ≤ i < NMAX
* @throws java.lang.IllegalArgumentException if key ≥ key associated with index i
* @throws java.util.NoSuchElementException no key is associated with index i
*/
public void decreaseKey(int i, Key key) {
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
if (keys[i].compareTo(key) <= 0) throw new IllegalArgumentException("Calling decreaseKey() with given argument would not strictly decrease the key"); keys[i] = key;
sink(qp[i]);
} /**
* Remove the key associated with index i.
* @param i the index of the key to remove
* @throws java.lang.IndexOutOfBoundsException unless 0 ≤ i < NMAX
* @throws java.util.NoSuchElementException no key is associated with index i
*/
public void delete(int i) {
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
int index = qp[i];
exch(index, N--);
swim(index);
sink(index);
keys[i] = null;
qp[i] = -1;
} /**************************************************************
* General helper functions
**************************************************************/
private boolean less(int i, int j) {
return keys[pq[i]].compareTo(keys[pq[j]]) < 0;
} private void exch(int i, int j) {
int swap = pq[i]; pq[i] = pq[j]; pq[j] = swap;
qp[pq[i]] = i; qp[pq[j]] = j;
} /**************************************************************
* Heap helper functions
**************************************************************/
private void swim(int k) {
while (k > 1 && less(k/2, k)) {
exch(k, k/2);
k = k/2;
}
} private void sink(int k) {
while (2*k <= N) {
int j = 2*k;
if (j < N && less(j, j+1)) j++;
if (!less(k, j)) break;
exch(k, j);
k = j;
}
} /***********************************************************************
* Iterators
**********************************************************************/ /**
* Returns an iterator that iterates over the keys on the
* priority queue in descending order.
* The iterator doesn't implement <tt>remove()</tt> since it's optional.
* @return an iterator that iterates over the keys in descending order
*/
public Iterator<Integer> iterator() { return new HeapIterator(); } private class HeapIterator implements Iterator<Integer> {
// create a new pq
private IndexMaxPQ<Key> copy; // add all elements to copy of heap
// takes linear time since already in heap order so no keys move
public HeapIterator() {
copy = new IndexMaxPQ<Key>(pq.length - 1);
for (int i = 1; i <= N; i++)
copy.insert(pq[i], keys[pq[i]]);
} public boolean hasNext() { return !copy.isEmpty(); }
public void remove() { throw new UnsupportedOperationException(); } public Integer next() {
if (!hasNext()) throw new NoSuchElementException();
return copy.delMax();
}
} /**
* Unit tests the <tt>IndexMaxPQ</tt> data type.
*/
public static void main(String[] args) {
// insert a bunch of strings
String[] strings = { "it", "was", "the", "best", "of", "times", "it", "was", "the", "worst" }; IndexMaxPQ<String> pq = new IndexMaxPQ<String>(strings.length);
for (int i = 0; i < strings.length; i++) {
pq.insert(i, strings[i]);
} // print each key using the iterator
for (int i : pq) {
StdOut.println(i + " " + strings[i]);
} StdOut.println(); // increase or decrease the key
for (int i = 0; i < strings.length; i++) {
if (StdRandom.uniform() < 0.5)
pq.increaseKey(i, strings[i] + strings[i]);
else
pq.decreaseKey(i, strings[i].substring(0, 1));
} // delete and print each key
while (!pq.isEmpty()) {
String key = pq.maxKey();
int i = pq.delMax();
StdOut.println(i + " " + key);
}
StdOut.println(); // reinsert the same strings
for (int i = 0; i < strings.length; i++) {
pq.insert(i, strings[i]);
} // delete them in random order
int[] perm = new int[strings.length];
for (int i = 0; i < strings.length; i++)
perm[i] = i;
StdRandom.shuffle(perm);
for (int i = 0; i < perm.length; i++) {
String key = pq.keyOf(perm[i]);
pq.delete(perm[i]);
StdOut.println(perm[i] + " " + key);
} }
}
IndexMaxPQ.java
2.4.4.7 索引有限队列用例
下面的用例调用了IndexMinPQ的代码Multiway解决了多项归并问题:它将多个有序的输入流归并成一个有序的输出流。许多应用中都会遇到这个问题。输入可能你来自多种科学仪器的输出(按照时间排序),或是来自多个音乐或电影网站的信息列表(按名称或艺术家名字排列),或是商业交易(按账号或时间排序),或者其他。如果有足够的空间,你可以把它们简单地读入一个数组并排序,但如果用例优先队列,无论输入有多长你都可以把它们全部读入并排序。
/**
* The <tt>Multiway</tt> class provides a client for reading in several
* sorted text files and merging them together into a single sorted
* text stream.
* This implementation uses a {@link IndexMinPQ} to perform the multiway
* merge.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/24pq">Section 2.4</a>
* of <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/ public class Multiway { // This class should not be instantiated.
private Multiway() { } // merge together the sorted input streams and write the sorted result to standard output
private static void merge(In[] streams) {
int N = streams.length;
IndexMinPQ<String> pq = new IndexMinPQ<String>(N);
for (int i = 0; i < N; i++)
if (!streams[i].isEmpty())
pq.insert(i, streams[i].readString()); // Extract and print min and read next from its stream.
while (!pq.isEmpty()) {
StdOut.print(pq.minKey() + " ");
int i = pq.delMin();
if (!streams[i].isEmpty())
pq.insert(i, streams[i].readString());
}
StdOut.println();
} /**
* Reads sorted text files specified as command-line arguments;
* merges them together into a sorted output; and writes
* the results to standard output.
* Note: this client does not check that the input files are sorted.
*/
public static void main(String[] args) {
int N = args.length;
In[] streams = new In[N];
for (int i = 0; i < N; i++)
streams[i] = new In(args[i]);
merge(streams);
}
}
Multiway.java
这段代码调用了IndexMinPQ()来将作为命令行参数输入的多行有序字符串归并为一行有序的输出。每个输入流的索引都关联着一个元素(输入中的下个字符串)。初始化之后,代码进入一个循环,删除并打印出队列中最小的字符串,然后将该输入的下一个字符串添加为一个元素。