// 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); } static void mergesort(Elem[] array, Elem[] temp, int l, int r) { int mid = (l+r)/2; // Select midpoint if (l == r) return; // List has one element mergesort(array, temp, l, mid); // Mergesort first half mergesort(array, temp, mid+1, r); // Mergesort second half for (int i=l; i<=r; i++) // Copy subarray to temp temp[i] = array[i]; // Do the merge operation back to array int i1 = l; int i2 = mid + 1; for (int curr=l; curr<=r; curr++) { if (i1 == mid+1) // Left sublist exhausted array[curr] = temp[i2++]; else if (i2 > r) // Right sublist exhausted array[curr] = temp[i1++]; else if (temp[i1].key() < temp[i2].key()) // Get smaller value array[curr] = temp[i1++]; else array[curr] = temp[i2++]; } } // 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