多路使用优先级队列

时间:2017-08-05 13:47:41

标签: java algorithm merge priority-queue

这是Sedgewick的一个例子; Wayne:算法第4版。但我无法弄明白。请帮助!

以下是代码:

package algorithm2_4;

import chap1.*;

public class Multiway {
private Multiway() {
}

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());
    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.
 *
 * @param args
 *            the command-line arguments
 */
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);
}
}

如果
多%m1.txt
A C D E
%更多m2.txt
B S Z

然后
%java Multiway m1.txt m2.txt
A B C D E S Z

顺便说一句,IndexMinPQ是下面IndexMinPQ API的基于堆的实现 我不太明白为什么上面的代码可以将几个排序列表合并为一个 有人可以向我解释一下吗?

  

  class IndexMinPQ<Item extends Comparable<Item>>

           

  IndexMinPQ(int maxN)   创建容量优先级队列 maxN
      可能包含 0 maxN-1之间的索引。     void insert(int k, Item item)  插入 item ;将其与 k联系起来     void change(int k, Item item)  将与 k 相关联的项目更改为 item
   boolean contains(int k)   k 与某个项目相关联吗?
    void delete(int k)   删除 k 及其相关项
    Item min()   返回最小项目
    int minIndex()   返回最小项目的索引
    int delMin()   删除最小项并返回其索引
   boolean isEmpty()   优先级队列是空的吗?
    int size()   优先级队列中的项目数

0 个答案:

没有答案
相关问题