// 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. // First, generate a series of initial runs using Quicksort. // Then, do a single multi-way merge pass. // The records are simply an int value interger values. public class Exmrg3 { static final int NumRec = 1024; // Number of records in a block static final int bufblocks = 32; // Number of blocks in the buffer (run) ////// Code for Quicksort //////////////////////////////////// static void swap(int[] array, int p1, int p2) { int temp = array[p1]; array[p1] = array[p2]; array[p2] = temp; } static int partition(int[] array, int l, int r, int pivot) { do { // Move the bounds inward until they meet while (array[++l] < pivot); // Move left bound right while ((r!=0) && (array[--r]>pivot)); // Move right bound swap(array, l, r); // Swap out-of-place values } while (l < r); // Stop when they cross swap(array, l, r); // Reverse last, wasted swap return l; // Return first position in right partition } static void qsort(int[] array, int i, int j) { // Quicksort int pivotindex = (i+j)/2; swap(array, pivotindex, j); // Stick pivot at end // k will be the first position in the right subarray int k = partition(array, i-1, j, array[j]); swap(array, k, j); // Put pivot in place if ((k-i) > 1) qsort(array, i, k-1); // Sort left partition if ((j-k) > 1) qsort(array, k+1, j); // Sort right partition } ////// End code for Quicksort //////////////////////////////// // Use quicksort to generate initial runs, placing the runs // one after another into the temporary file. static void firstpass(DataInputStream in, DataOutputStream out, int numrecs) throws IOException { int bufrecs = NumRec * bufblocks; int[] buffer = new int[bufrecs]; int runs = 2*numrecs/bufrecs; System.out.println("Number of records: " + numrecs*2); System.out.println("Number of runs: " + runs); for (int i=0; i "); int filesize = Integer.parseInt(args[2]); 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(); } }