/** Source code example for "A Practical Introduction to Data Structures and Algorithm Analysis, 3rd Edition (Java)" by Clifford A. Shaffer Copyright 2008-2011 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 = 0; static > void Sort(E[] A) { qsort(A, 0, A.length-1); } static int MAXSTACKSIZE = 1000; static > void inssort(E[] A) { for (int i=1; i0) && (A[j].compareTo(A[j-1]) < 0); j--) DSutil.swap(A, j, j-1); } /** Non-recursive Quicksort */ static > void qsort(E[] A, int oi, int oj) { int[] Stack = new int[MAXSTACKSIZE]; // Stack for array bounds int listsize = oj-oi+1; int top = -1; E pivot; int pivotindex, l, r; Stack[++top] = oi; // Initialize stack Stack[++top] = oj; while (top > 0) { // While there are unprocessed subarrays // Pop Stack int j = Stack[top--]; int i = Stack[top--]; // Findpivot pivotindex = (i+j)/2; pivot = A[pivotindex]; DSutil.swap(A, pivotindex, j); // Stick pivot at end // Partition l = i-1; r = j; do { while (A[++l].compareTo(pivot)<0); while ((r!=0) && (A[--r].compareTo(pivot)>0)); DSutil.swap(A, l, r); } while (l < r); DSutil.swap(A, l, r); // Undo final swap DSutil.swap(A, 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(A); // Final Insertion Sort } public static void main(String args[]) throws IOException { assert args.length >= 1 : "Usage: Sortmain [+/-] "; System.out.println("Args: " + args.length); 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++; } ARRAYSIZE = Integer.parseInt(args[currarg++]); if (args.length > currarg) THRESHOLD = Integer.parseInt(args[currarg]); Integer[] A = new Integer[ARRAYSIZE]; System.out.println("Input: " + input + ", size: " + ARRAYSIZE + ", threshold: " + THRESHOLD); if (input == -1) for (i=0; i 0) { System.out.println("OOPS -- bad sort algorithm!"); for (int j=0; j