// 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 // Sorting main function for testing correctness of sort algorithm. // To use: [+/-] // + means increasing values, - means decreasing value and no // parameter means random values; // where controls the number of objects to be sorted; // and controls the threshold parameter for certain sorts, e.g., // cutoff point for quicksort sublists. import java.io.*; public class Sortmain { static int THRESHOLD = 0; static int ARRAYSIZE = 10000; static void sort(Elem[] array) { Elem[] temp = new Elem[ARRAYSIZE]; mergesort(array, temp, 0, array.length-1); } // Insertion Sort for subarrays: sort len elements from index start static void inssort(Elem[] array, int start, int len) { for (int i=start+1; istart) && (array[j].key()= THRESHOLD) mergesort(array, temp, l, mid); else inssort(array, l, mid-l+1); if ((r-mid) > THRESHOLD) mergesort(array, temp, mid+1, r); else inssort(array, mid+1, r-mid); // Do the merge operation. First, copy 2 halves to temp. for (i=l; i<=mid; i++) temp[i] = array[i]; for (j=1; j<=r-mid; j++) temp[r-j+1] = array[j+mid]; // Merge sublists back to array int a = temp[l].key(); int b = temp[r].key(); for (i=l,j=r,k=l; k<=r; k++) if (a < b) { array[k] = temp[i++]; a = temp[i].key(); } else { array[k] = temp[j--]; b = temp[j].key(); } } // Main routine for sorting class driver // This is the version for running timings public static void main(String args[]) throws IOException { Assert.notFalse(args.length >= 1, "Usage: Sortmain [+/-] "); int i; int input = 0; int currarg = 0; if (args[currarg].charAt(0) == '+') { input = 1; currarg++; } else if (args[currarg].charAt(0) == '-') { input = -1; currarg++; } int ARRAYSIZE = Integer.parseInt(args[currarg++]); if (args.length > currarg) THRESHOLD = Integer.parseInt(args[currarg]); Elem[] array = new Elem[ARRAYSIZE]; System.out.println("Input: " + input + ", size: " + ARRAYSIZE + ", threshold: " + THRESHOLD); if (input == -1) for (i=0; i