/** * A quick sort demonstration algorithm * SortAlgorithm.java * Adapted by Rich Vuduc and Kathy Yelick from the original, October 1997 * * @author James Gosling * @author Kevin A. Smith * */ public class QSort { /** This is a generic version of C.A.R Hoare's Quick Sort * algorithm. This will handle arrays that are already * sorted, and arrays with duplicate keys.
* * If you think of a one dimensional array as going from * the lowest index on the left to the highest index on the right * then the parameters to this function are lowest index or * left and highest index or right. The first time you call * this function it will be with the parameters 0, a.length - 1. * * @param a an intr array * @param low left boundary of array partition * @param high right boundary of array partition */ public static void quicksort(MatrixEntry [1d] a, int low, int high) { // If there are fewer than two elements, do nothing. if (low < high) { int pivotIndex = (low + high)/2; MatrixEntry pivot = a[pivotIndex]; a[pivotIndex] = a[high]; // Swap pivot with last item a[high] = pivot; int i = low - 1; int j = high; do { do { i++; } while (a[i].compare(pivot) < 0); do { j--; } while ((pivot.compare(a[j]) < 0) && (j > low)); if (i < j) { swap(a, i, j); } } while (i < j); a[high] = a[i]; a[i] = pivot; // Put pivot in the middle where it belongs quicksort(a, low, i - 1); // Recursively sort left list quicksort(a, i + 1, high); // Recursively sort right list } } private static void swap(MatrixEntry [1d] a, int i, int j) { MatrixEntry tmp; tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void sort(MatrixEntry [1d] a) { quicksort(a, a.domain().min()[1], a.domain().max()[1]); } }