/** * Find the subscript of the largest entry. Used by selSort() */ static int maxIdx ( Comparable[] x, int n ) { int big = 0, // Subscript of largest encountered k; // Loop variable for ( k = 1; k < n; k++ ) // Start at 1 --- no need to check 0 if ( x[big].compareTo(x[k]) < 0 ) // I.e., NOT the biggest so far big = k; return big; } // end maxIdx() /** * Swap two array entries. Used by selSort() */ static void swap ( Comparable[] x, int p, int q ) { Comparable t = x[p]; x[p] = x[q]; x[q] = t; } /** * Recursive selection sort --- NOT the recommended formulation ! ! ! */ static void selSort ( Comparable[] x, int size ) { if ( size > 1 ) { int j = maxIdx ( x, size ); // Subscript of largest entry swap ( x, size-1, j ); // Move to end of the array selSort ( x, size-1 ); // Recursively sort the front end // NOTE: tail recursion, easy optim. } // end if ( size > 1 ) // else is ignored --- array of 0 or 1 entries is already sorted } // end selSort()