001package algs24;
002import stdlib.*;
003/* ***********************************************************************
004 *  Compilation:  javac Multiway.java
005 *  Execution:    java Multiway input1.txt input2.txt input3.txt ...
006 *  Dependencies: IndexMinPQ.java In.java StdOut.java
007 *
008 *  Merges together the sorted input stream given as command-line arguments
009 *  into a single sorted output stream on standard output.
010 *
011 *  % more m1.txt
012 *  A B C F G I I Z
013 *
014 *  % more m2.txt
015 *  B D H P Q Q
016 *
017 *  % more m3.txt
018 *  A B E F J N
019 *
020 *  % java Multiway m1.txt m2.txt m3.txt
021 *  A A B B B C D E F F G H I I J N P Q Q Z
022 *
023 *************************************************************************/
024
025public class Multiway {
026
027        public static void merge(In[] streams) {
028                int N = streams.length;
029                IndexMinPQ<String> pq = new IndexMinPQ<>(N);
030
031                // read the first String from each stream
032                for (int i = 0; i < N; i++)
033                        if (!streams[i].isEmpty())
034                                pq.insert(i, streams[i].readString());
035
036                // Extract and print min and read next from its stream.
037                while (!pq.isEmpty()) {
038                        StdOut.print(pq.minKey() + " ");
039                        int i = pq.delMin();
040                        if (!streams[i].isEmpty())
041                                pq.insert(i, streams[i].readString());
042                }
043                StdOut.println();
044        }
045
046        public static void main(String[] args) {
047                args = new String[] { "data/m1.txt", "data/m2.txt", "data/m3.txt" };
048                int N = args.length;
049                In[] streams = new In[N];
050                for (int i = 0; i < N; i++)
051                        streams[i] = new In(args[i]);
052                merge(streams);
053        }
054}