// 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 inssort(Elem[] array) { // Insertion Sort for (int i=1; i0) && (array[j].key() 0) { // While there are unprocessed subarrays // Pop Stack int j = Stack[top--]; int i = Stack[top--]; // Findpivot pivotindex = (i+j)/2; pivot = array[pivotindex].key(); DSutil.swap(array, pivotindex, j); // Stick pivot at end // Partition l = i-1; r = j; do { while (array[++l].key() < pivot); while ((r!=0) && (array[--r].key() > pivot)); DSutil.swap(array, l, r); } while (l < r); DSutil.swap(array, l, r); // Undo final swap DSutil.swap(array, l, j); // Put pivot value in place // Put new subarrays onto Stack if they are small if ((l-i) > THRESHOLD) { // Left partition Stack[++top] = i; Stack[++top] = l-1; } if ((j-l) > THRESHOLD) { // Right partition Stack[++top] = l+1; Stack[++top] = j; } } inssort(array); // Final Insertion Sort } // 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