<QuickSort>=
public void quickSort(String[] words, int first, int last) {
if (first < last) {
<Partition the array around a pivot>
quickSort(words, first, pivot-1);
quickSort(words, pivot+1, last);
}
}
The code's syntax, on an initial call with first=0 and last = n-1, leads to the recurrence [*] T(n) = T(p) + T(n-p-1) + cost of partitioning the array where p is the pivot index. Since this pivot position is not known in advance, unlike mergeSort() where the array was always split into two (almost) equal parts, quickSort() can have variable performance. As we will see later [->], in the best case p=n/2, and in the worst case p=1.
Let's first develop the partition() routine, and then analyze the recurrence. This code is from Bentley's Programming Pearls [cite bent:86], and he attributes it to Nico Lumuto.
<Partition the array around a pivot>= (<-U)
int pivot = first;
int i;
for (i = first + 1; i <= last; i++) {
if (words[i].compareTo(words[first]) < 0) {
++pivot;
<Swap words[pivot] and words[i]>
}
}
i = first;
<Swap words[pivot] and words[i]>
Rather than write a swap() routine, we'll just hard-code it.
<Swap words[pivot] and words[i]>= (<-U) String temp = words[pivot]; words[pivot] = words[i]; words[i] = temp;