red
public class ModifiedQuickSort
{
// data member
static Comparable [] a; // array of elements to be sorted
/** sort the elements a[0 : a.length - 1] using the quick sort method */
public static void quickSort(Comparable [] a)
{
ModifiedQuickSort.a = a;
if (a.length <= 1) return;
// move largest element to right end
MyMath.swap(a, a.length - 1, MyMath.max(a, a.length - 1));
quickSort(0, a.length - 2);
}
/** sort a[l:r], a[r+1] >= a[l:r] */
private static void quickSort(int l, int r)
{
while (leftEnd < rightEnd)
{// at least 2 elements to sort
int leftCursor = leftEnd, // left-to-right cursor
rightCursor = rightEnd + 1; // right-to-left cursor
Comparable pivot = a[leftEnd];
// swap elements >= pivot on left side
// with elements <= pivot on right side
while (true)
{
do
{// find >= element on left side
leftCursor++;
} while (a[leftCursor].compareTo(pivot) < 0);
do
{// find <= element on right side
rightCursor--;
} while (a[rightCursor].compareTo(pivot) > 0);
if (leftCursor >= rightCursor) break; // swap pair not found
MyMath.swap(a, leftCursor, rightCursor);
}
// place pivot
a[leftEnd] = a[rightCursor];
a[rightCursor] = pivot;
quickSort(leftEnd, rightCursor - 1); // sort left segment
leftEnd = rightCursor + 1; // set to sort right segment
}
}
}
The modified code is expected to run slightly faster than Program 19.6
because the overhead of a while
is less than that of a method call for most compilers.