61
Quicksort
Now find the elements smaller than the pivot
and the elements larger
than the pivot.
This is called
partitioning.
Now you have
• A sub-array of all the numbers less than the pivot
•
The pivot
• A sub-array of all the numbers greater than the pivot
The two sub-arrays aren’t sorted. They’re just partitioned. But if they
were
sorted, then sorting the whole array would be pretty easy.
If the sub-arrays are sorted, then you can combine
the whole thing like
this—
left array + pivot + right array
—and you get a sorted
array. In this case, it’s
[10, 15] + [33] + [] =
[10, 15, 33]
, which is a sorted array.
How do you sort the sub-arrays? Well, the
quicksort base case already
knows how to sort arrays of two elements (the left sub-array) and
empty arrays (the right sub-array). So if you call quicksort on the two
sub-arrays and then combine the results, you get a sorted array!
quicksort([15, 10]) + [33] + quicksort([])
> [10, 15, 33]
A sorted array
62
Chapter 4
I
Quicksort
This will work with any pivot. Suppose you choose 15 as the
pivot instead.
Both sub-arrays
have only one element, and you know how to sort
those. So now you know how to sort an array of three elements. Here
are the steps:
1. Pick a pivot.
2. Partition the array into two sub-arrays: elements less than the pivot
and elements greater than the pivot.
3. Call quicksort recursively on the two sub-arrays.
What about an array of four elements?
Suppose you choose 33 as the pivot again.
The array on the left has three elements. You already know how to sort
an array of three elements: call quicksort on it recursively.
63
Quicksort
So you can sort an array of four elements. And
if you can sort an array
of four elements, you can sort an array of five elements. Why is that?
Suppose you have this array of five elements.
Here are all the ways you can partition this array, depending on what
pivot you choose.
Notice that all of these sub-arrays have somewhere between 0 and 4
elements. And you already know how to sort an array of 0 to 4
elements
using quicksort! So no matter what pivot you pick, you can call
quicksort recursively on the two sub-arrays.