import java.util.Arrays; public class QuickSortClean { /* ------------------------------------------------------- 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; while (low <= high) { if ( A[high].compareTo(pivot) >= 0 ) { high--; } else { exch(A, low, high); low++; } } exch(A, s, high); return high; } public static > void exch(T[] A, int i, int j) { T h = A[i]; A[i] = A[j]; A[j] = h; } }