[   ^ to index...   |   <-- previous   ]

Quicksort

IDEA: "Select an element X, called the pivot. Divide all the other elements into two piles: all elements <= X, and all elements > X. We now know exactly which location X should go into (why?), so put it there and sort the remaining two piles."

In practice, we do not simply loop through each element and consign it to a "left" pile or a "right" pile. Instead, we observe that many items will probably already be in their proper place, either to the left of the expected position of the pivot or to the right of it.

Therefore, we loop down the left and right sides until we find two elements that we need to swap, and then we swap them.

We proceed like this until our "left" and "right" cursors meet, and the meeting point will be where we place the pivot element.

Analaysis

On average, we will select an item in the middle of the array. Each partition step is O(n); we do this O(logn) times, so the result is O(nlogn).

In practice, quicksort is the fastest of the O(nlogn) sorts most of the time.

Caveats:

  • The pivot choice is crucial. The O(nlogn) property of quicksort comes from the fact that we split the array into two approximately equal halves, on average. We usually try to guarantee this by selecting, for example, 3 random array elements and using the median as the pivot.

  • In one particular situation, quicksort with a naive partition selection can be O(n^2). What is that situation?

[qsort stages diagram]

Last modified: Tue Aug 8 13:31:02 PDT 2000