import java.util.Arrays; public class QuickSort { /* ------------------------------------------------------- QuickSort: A[s.. e-1] ------------------------------------------------------ */ public static > void sort(T[] A, int s, int e) { if ( e - s <= 1 ) // Base case return; // No need to sort an array of 1 element... // Partition A using A[s] as pivot int pivotLoc = partition(A, s, e); sort(A, s, pivotLoc); // Sort left half with quick sort sort(A, pivotLoc+1, e); // Sort right half with quick sort } /* -------------------------------------------------------- Input: A[lo] .... A[hi-1] ^ | pivot Output: Partition A[s] ... A[e-1] so that: pivot = A[s] | values < pivot | A[s] | values > A[lo] | ^ | index k Returns: k --------------------------------------------------------- */ public static > int partition(T[] A, int s, int e) { T pivot = A[s]; int low = s+1, high = e-1; System.out.println("\npartition(A," + s + "," + e +"):"); System.out.print("Index --> "); for ( int k = 0; k < A.length; k++) System.out.print( k + " "); System.out.println(); while (low <= high) { // Show progress System.out.print(">>>> " + Arrays.toString(A)); System.out.print(" Pivot = " + pivot + " low = " + low + " high = " + high); if ( A[high].compareTo(pivot) >= 0 ) { System.out.println(" -- A[" + high + "] >= " + pivot); high--; } else { System.out.println(" ++ A[" + high + "] < " + pivot + (low==high ? " ##" : "") ); exch(A, low, high); low++; } } // Show progress System.out.print(">>>> " + Arrays.toString(A)); System.out.print(" Pivot = " + pivot + " low = " + low + " high = " + high); System.out.println(" ** exch pivot A[" + s + "] and A[" + high + "]"); exch(A, s, high); System.out.print("Output: " + Arrays.toString(A)); System.out.println("\n"); return high; } public static > void exch(T[] A, int i, int j) { T h = A[i]; A[i] = A[j]; A[j] = h; } }