Table of Contents
Quick sort is a sorting algorithm with the optimal O(n log n) average case, but a O(n^{2}) worst case.
Despite its slower worst case behavior, the Quick sort is generally preferred over Merge sort when sorting arraylike structures (including vectors and deques). This is because the constant multiplier on quick sort's average case is much smaller, and, if we are careful, we can make the worst case input of quick sort a relatively obscure case that would seldom be seen in practice.
Like Merge sort, Quick sort also works by dividing the array into progressively smaller parts, but instead of chopping at an arbitrary point (e.g., halfway), it divides into pieces in which
all items in the left section are less than or equal to a pivot value,
all items on the right are greater than the pivot value.
This is often called partitioning the array.
For example, given the array
1  4  3  9  5  8  7  6 
it's not hard to see that we can split the array this way


so that all items to the left are less than or equal to a pivot value 4, and all items on the right are greater than 4.
On the other hand, for some arrays:
9  1  8  7  2  6  4  0 
there's really no place were we can divide the array “as is” to meet these requirements.
So an algorithm to partition the array must, in some case, move
elements around to make the partition possible. The
pivotIndex
algorithm from your text does just
this.
In the Forum: