import java.util.Arrays; public class QuickSort2 { /* -------------------------------------------------------- More efficient way: ONLY swap A[low] and A[high] when A[low] > pivot A[high] < pivot --------------------------------------------------------- */ 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); // Find A[low] > pivot while ( low < high && A[low].compareTo(pivot) <= 0 ) { low++; } // Find A[high] < pivot while ( low < high && A[high].compareTo(pivot) >= 0 ) { high--; } // Swap A[low] and A[high] if ( low < high ) { System.out.println(" A[" + low + "] <--> " + " A[" + high + "]"); exch(A, low, high); low++; high--; } } // 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; } }