// 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) { qsort(array, 0, array.length-1); } static int MAXSTACKSIZE = 1000;static void qsort(Elem[] array, int i, int j) { // Quicksort int pivotindex = findpivot(array, i, j); // Pick a pivot DSutil.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].key()); DSutil.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 } static int partition(Elem[] array, int l, int r, int pivot) { do { // Move the bounds inward until they meet while (array[++l].key() < pivot); // Move left bound right while ((r!=0) && (array[--r].key()>pivot)); // Move right bound DSutil.swap(array, l, r); // Swap out-of-place values } while (l < r); // Stop when they cross DSutil.swap(array, l, r); // Reverse last, wasted swap return l; // Return first position in right partition } static int findpivot(Elem[] array, int i, int j) { return (i+j)/2; } // 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