// Note: In class, I did not have all of the inequalities // correct. The nuance in the implementation below is that // l and r must cross over in order for the outer loop to // terminate. In the case where the pivot is largest of all, // this will cause l to advance to position b, and thus the // final swap will swap the pivot with itself. // Quicksort elements of the array A between a and b inclusive void quicksort (int [] A, int a, int b) { if (a < b) { int pivot = A[b]; // or choose one element at random, swap into index b int l = a; int r = b-1; // Keep pivoting until the l and r indices cross over. while (l <= r) { while (l <= r && A[l] <= pivot) // slide l right until it points to an l++; // element larger than pivot while (l <= r && A[r] >= pivot) // slide r left until it points to an r--; // element smaller than pivot if (l < r) // swap out-of-order pairs swap (A[l], A[r]); } // Re-position the pivot into its correct slot swap (A[l], A[b]); quicksort (A, a, l-1); quicksort (A, l + 1, b); } }