Section 26.12 Quick Sort
With our partition algorithm in place, we can now implement . Here is the pseudocode:
QuickSort(list, start, end):
if start >= end:
return list // size 0/1 already sorted
else:
pivotLocation = Partition(list)
QuickSort(0 to pivotLocation - 1) // Sort the first half
QuickSort(pivotLocation to end) // Sort the second half
Implemented in C++ for a vector, it looks like this:
Again we use a wrapper function
quickSort(vector<T>& vec) to start the recursive quick sort function. It means that main does not have to provide the start and end indices.
Try running this interactive to see how the process plays out. As you do so, pay attention to when elements turn white. Those elements are in their final sorted position. Each partition step places one element (the pivot) into its final sorted position. Quick sort then recursively sorts the left and right partitions around that pivot.
This process is not stable. Say you had the partition:
5 1(A) 1(B) 10 15
The first swap would produce:
5 15 1(B) 10 1(A)
This reverses the order of the two 1s. Recall that any time elements are swapping across large distance without consideration for other βequalβ elements, an algorithm is going to almost certainly be unstable. This is the case for quick sort.
Checkpoint 26.12.1.
Which statements are true about quick sort?
- Quick sort is a divide-and-conquer algorithm.
- Quick sort uses a partitioning step to divide the list into two parts.
- Quick sort always partitions the list into two equal sized parts.
- Quick sort recursively sorts the left and right partitions around the pivot.
- Quick sort is stable.
You have attempted of activities on this page.
