// Source code example for "A Practical Introduction // to Data Structures and Algorithm Analysis" // by Clifford A. Shaffer, Prentice Hall, 1998. // Copyright 1998 by Clifford A. Shaffer import java.io.*; // External sort using mergesort. // Simply do a series of two-way merging passes. // The records are simply 2-byte interger values. public class Exmrg1 { static final int NumRec = 1024; // Number of records in a block public static String[] FName = new String[4]; // Indices for I/O files. // Use two input files and two output files. public static int IN1 = 0; public static int IN2 = 1; public static int OUT1 = 2; public static int OUT2 = 3; // Divide the records in the input file between the two // output files, leaving numrecs records in each. static void firstpass(DataInputStream in, DataOutputStream out1, DataOutputStream out2, int numrecs) throws IOException { int val; for (int i=0; i1; i/=2) { DataInputStream in1 = new DataInputStream( new BufferedInputStream(new FileInputStream(FName[IN1]))); DataInputStream in2 = new DataInputStream( new BufferedInputStream(new FileInputStream(FName[IN2]))); out1 = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(FName[OUT1]))); out2 = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(FName[OUT2]))); System.out.println("Do a pass"); dopass(in1, in2, out1, out2, i, recs/(2*i)); in1.close(); in2.close(); out1.close(); out2.close(); temp = IN1; IN1 = OUT1; OUT1 = temp; temp = IN2; IN2 = OUT2; OUT2 = temp; } // Finally, merge the last two runs into the output file DataInputStream in1 = new DataInputStream( new BufferedInputStream(new FileInputStream(FName[IN1]))); DataInputStream in2 = new DataInputStream( new BufferedInputStream(new FileInputStream(FName[IN2]))); out1 = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(outfile))); dopass(in1, in2, out1, null, 1, recs/2); in1.close(); in2.close(); out1.close(); } public static void main(String args[]) throws IOException { byte[] buf = new byte[4*NumRec]; int[] intbuf = new int[NumRec]; Assert.notFalse(args.length == 3, "Usage: Exmrg1 "); int filesize = Integer.parseInt(args[2]); FName[IN1] = args[0] + ".1"; FName[IN2] = args[0] + ".2"; FName[OUT1] = args[1] + ".1"; FName[OUT2] = args[1] + ".2"; File f = new File(FName[IN1]); if (f.exists()) f.delete(); f = new File(FName[IN2]); if (f.exists()) f.delete(); f = new File(FName[OUT1]); if (f.exists()) f.delete(); f = new File(FName[OUT2]); if (f.exists()) f.delete(); long time1 = System.currentTimeMillis(); exmergesort(args[0], args[1], filesize*NumRec); long time2 = System.currentTimeMillis(); System.out.println("Time is " + (time2-time1)); System.in.read(); } }