In the original implementation of QuickSort, the first element in the array was picked as pivot, as is done on line 3 above. Below, the red bar indicates the choice of pivot. At each step of the algorithm, it is at the left of the array being sorted:
Choosing the first element as pivot can generate extra work when the array is already (partially) sorted. Rather than picking the first element, the middle element can be chosen, behaving better on already sorted arrays:
When choosing the value in the middle of the array as pivot, yields the following result, with again the red bar indicating the pivot:
Rather than pick the middle element as pivot, a random value can be picked from the array:
The pivot is now picked randomly as shown in the visualization below:
The final approach to pivot selection we will look at was invented by Robert Sedgewick and involves picking the median of three values:
The pivot is now picked by looking at three different values as shown in the visualization below:
Aside from how we pick the pivot, all versions of QuickSort shown above have the same thing in common that they use recursion for implementing the divide and conquer tactic. Recursion has overhead in that new stackframes need to be constructed for each call. Recursion also limits the maximum size of the array we can sort, but that is more of a theoretical challenge.
QuickSort can also be implement without using recursion, by using a user-defined stack to keep track of the work to be done. A possible implementation:
And the execution (this time using the first element as pivot again):
In general, QuickSort is not a stable sort. Elements of equal value are not guaranteed to remain in their original sort order for most implementations. However, the implementations above keep the elements that are equal to the pivot in the original order as they were found. That makes the above implementation stable.
Check out more algorithm visualizations at PyAlgoViz.
Python code styled as tango by hilite.me with border:1px solid #ddd;padding:11px 7px;