# Quicksort

Class Quicksort in action on a list of numbers. The horizontal lines are pivot values. Sorting algorithm Varies Θ(n2) Θ(nlogn) Θ(nlogn) comparisons Varies by implementation Sometimes This box: view • talk

Quicksort is a well-known sorting algorithm developed by C. A. R. Hoare that, on average, makes Θ(nlogn) (big O notation) comparisons to sort n items. However, in the worst case, it makes Θ(n2) comparisons. Typically, quicksort is significantly faster in practice than other Θ(nlogn) algorithms, because its inner loop can be efficiently implemented on most architectures, and in most real-world data, it is possible to make design choices which minimize the probability of requiring quadratic time.

Quicksort is a comparison sort and, in efficient implementations, is not a stable sort.

## History

The quicksort algorithm was developed by C. A. R. Hoare in 1962 while in Russia, as a visiting student at Moscow State University. At that time, Hoare worked in a project on machine translation for the National Physical Laboratory. He developed the algorithm in order to sort the words to be translated, to make them more easily matched to an already-sorted Russian-to-English dictionary that was stored on magnetic tape[1].

## Algorithm

Quicksort sorts by employing a divide and conquer strategy to divide a list into two sub-lists.

Full example of quicksort on a random set of numbers. The boxed element is the pivot. It is always chosen as the last element of the partition.

The steps are:

1. Pick an element, called a pivot, from the list.
2. Reorder the list so that all elements which are less than the pivot come before the pivot and so that all elements greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
3. Recursively sort the sub-list of lesser elements and the sub-list of greater elements.

The base case of the recursion are lists of size zero or one, which are always sorted.

In simple pseudocode, the algorithm might be expressed as this:

 function quicksort(array)
var list less, greater
if length(array) ≤ 1
return array
select and remove a pivot value pivot from array
for each x in array
if x ≤ pivot then append x to less
else append x to greater
return concatenate(quicksort(less), pivot, quicksort(greater))


Notice that we only examine elements by comparing them to other elements. This makes quicksort a comparison sort. This version is also a stable sort (assuming that the "for each" method retrieves elements in original order, and the pivot selected is the last among those of equal value).

The correctness of the partition algorithm is based on the following two arguments:

• At each iteration, all the elements processed so far are in the desired position: before the pivot if less than or equal to the pivot's value, after the pivot otherwise (loop invariant).
• Each iteration leaves one fewer element to be processed (loop variant).

The correctness of the overall algorithm follows from inductive reasoning: for zero or one element, the algorithm leaves the data unchanged; for a larger data set it produces the concatenation of two parts, elements less than or equal to the pivot and elements greater than it, themselves sorted by the recursive hypothesis.

The disadvantage of the simple version above is that it requires Ω(n) extra storage space, which is as bad as merge sort. The additional memory allocations required can also drastically impact speed and cache performance in practical implementations. There is a more complex version which uses an in-place partition algorithm and can achieve the complete sort using O(nlogn) space use on average (for the call stack):

  function partition(array, left, right, pivotIndex)
pivotValue := array[pivotIndex]
swap array[pivotIndex] and array[right] // Move pivot to end
storeIndex := left
for i  from  left to right − 1
if array[i] ≤ pivotValue
swap array[i] and array[storeIndex]
storeIndex := storeIndex + 1
swap array[storeIndex] and array[right] // Move pivot to its final place
return storeIndex

In-place partition in action on a small list. The boxed element is the pivot element, blue elements are less or equal, and red elements are larger.

This is the in-place partition algorithm. It partitions the portion of the array between indexes left and right, inclusively, by moving all elements less than or equal to a[pivotIndex] to the beginning of the subarray, leaving all the greater elements following them. In the process it also finds the final position for the pivot element, which it returns. It temporarily moves the pivot element to the end of the subarray, so that it doesn't get in the way. Because it only uses exchanges, the final list has the same elements as the original list. Notice that an element may be exchanged multiple times before reaching its final place.

This form of the partition algorithm is not the original form; multiple variations can be found in various textbooks, such as versions not having the storeIndex. However, this form is probably the easiest to understand.

Once we have this, writing quicksort itself is easy:

 procedure quicksort(array, left, right)
if right > left
select a pivot index (e.g. pivotIndex := left)
pivotNewIndex := partition(array, left, right, pivotIndex)
quicksort(array, left, pivotNewIndex - 1)
quicksort(array, pivotNewIndex + 1, right)


However, since partition reorders elements within a partition, this version of quicksort is not a stable sort.

### Parallelizations

Like merge sort, quicksort can also be easily parallelized due to its divide-and-conquer nature. Individual in-place partition operations are difficult to parallelize, but once divided, different sections of the list can be sorted in parallel. If we have p processors, we can divide a list of n elements into p sublists in Θ(n) average time, then sort each of these in $\textstyle\Theta\left(\frac{n}{p} \log\frac{n}{p}\right)$ average time. Ignoring the Θ(n) preprocessing, this is linear speedup. Given n processors, only Θ(n) time is required overall.

One advantage of parallel quicksort over other parallel sort algorithms is that no synchronization is required. A new thread is started as soon as a sublist is available for it to work on and it does not communicate with other threads. When all threads complete, the sort is done.

Other more sophisticated parallel sorting algorithms can achieve even better time bounds.[2] For example, in 1991 David Powers described a parallelized quicksort that can operate in O(logn) time given enough processors by performing partitioning implicitly.[3]

## Formal analysis

From the initial description it's not obvious that quicksort takes Θ(nlogn) time on average. It's not hard to see that the partition operation, which simply loops over the elements of the array once, uses Θ(n) time. In versions that perform concatenation, this operation is also Θ(n).

In the best case, each time we perform a partition we divide the list into two nearly equal pieces. This means each recursive call processes a list of half the size. Consequently, we can make only logn nested calls before we reach a list of size 1. This means that the depth of the call tree is Θ(logn). But no two calls at the same level of the call tree process the same part of the original list; thus, each level of calls needs only Θ(n) time all together (each call has some constant overhead, but since there are only Θ(n) calls at each level, this is subsumed in the Θ(n) factor). The result is that the algorithm uses only Θ(nlogn) time.

An alternate approach is to set up a recurrence relation for the T(n) factor, the time needed to sort a list of size n. Because a single quicksort call involves Θ(n) factor work plus two recursive calls on lists of size n / 2 in the best case, the relation would be:

$T(n) = \Theta(n) + 2T\left(\frac{n}{2}\right).$

The master theorem tells us that T(n) = Θ(nlogn).

In fact, it's not necessary to divide the list this precisely; even if each pivot splits the elements with 99% on one side and 1% on the other (or any other fixed fraction), the call depth is still limited to 100logn, so the total running time is still Θ(nlogn).

In the worst case, however, the two sublists have size 1 and n − 1 (for example, if the array consists of the same element by value), and the call tree becomes a linear chain of n nested calls. The ith call does Θ(ni) work, and $\sum_{i=0}^n (n-i) = \Theta(n^2)$. The recurrence relation is:

T(n) = Θ(n) + T(0) + T(n − 1) = O(n) + T(n − 1)

This is the same relation as for insertion sort and selection sort, and it solves to T(n) = Θ(n2). Given knowledge of which comparisons are performed by the sort, there are adaptive algorithms that are effective at generating worst-case input for quicksort on-the-fly, regardless of the pivot selection strategy.[4]

### Randomized quicksort expected complexity

Randomized quicksort has the desirable property that it requires only Θ(nlogn) expected time, regardless of the input. But what makes random pivots a good choice?

Suppose we sort the list and then divide it into four parts. The two parts in the middle will contain the best pivots; each of them is larger than at least 25% of the elements and smaller than at least 25% of the elements. If we could consistently choose an element from these two middle parts, we would only have to split the list at most 2log2n times before reaching lists of size 1, yielding an Θ(nlogn) algorithm.

A random choice will only choose from these middle parts half the time. However, this is good enough. Imagine that you are flipping a coin over and over until you get k heads. Although this could take a long time, on average only 2k flips are required, and the chance that you won't get k heads after 100k flips is highly improbable. By the same argument, quicksort's recursion will terminate on average at a call depth of only 2(2log2n). But if its average call depth is Θ(logn), and each level of the call tree processes at most n elements, the total amount of work done on average is the product, Θ(nlogn). Note that the algorithm does not have to verify that the pivot is in the middle half - if we hit it any constant fraction of the times, that is enough for the desired complexity.

The outline of a formal proof of the O(nlogn) expected time complexity follows. Assume that there are no duplicates as duplicates could be handled with linear time pre- and post-processing, or considered cases easier than the analyzed. Choosing a pivot, uniformly at random from 0 to n − 1, is then equivalent to choosing the size of one particular partition, uniformly at random from 0 to n − 1. With this observation, the continuation of the proof is analogous to the one given in the average complexity section.

### Average complexity

Even if pivots aren't chosen randomly, quicksort still requires only Θ(nlogn) time over all possible permutations of its input. Because this average is simply the sum of the times over all permutations of the input divided by n factorial, it's equivalent to choosing a random permutation of the input. When we do this, the pivot choices are essentially random, leading to an algorithm with the same running time as randomized quicksort.

More precisely, the average number of comparisons over all permutations of the input sequence can be estimated accurately by solving the recurrence relation:

$C(n) = n - 1 + \frac{1}{n} \sum_{i=0}^{n-1} (C(i)+C(n-i-1)) = 2n \ln n = 1.39n \log_2 n.$

Here, n − 1 is the number of comparisons the partition uses. Since the pivot is equally likely to fall anywhere in the sorted list order, the sum is averaging over all possible splits.

This means that, on average, quicksort performs only about 39% worse than the ideal number of comparisons, which is its best case. In this sense it is closer to the best case than the worst case. This fast average runtime is another reason for quicksort's practical dominance over other sorting algorithms.

\begin{align} C(n) &= (n-1) + C \cdot \frac{n}{2} + C \cdot \frac{n}{2}\\ &= (n-1) + 2C \cdot \frac{n}{2}\\ &= (n-1) + 2\left(\frac{n}{2} - 1 + 2C \cdot \frac{n}{4} \right)\\ &= n + n + 4C \cdot \frac{n}{4} - 1 - 2\\ &= n + n + n + 8C \cdot \frac{n}{8} - 1 - 2 - 4\\ &= \cdots\\ &= kn + 2^kC \cdot \frac{n}{2^k} - (1 + 2 + 4 + \cdots + 2^{k-1}), \mbox{ where } \log_2 n > k > 0\\ &= kn + 2^kC \cdot \frac{n}{2^k} - 2^k + 1, \rightarrow n \log_2 n + nC(1) - n + 1. \end{align}

### Space complexity

The space used by quicksort depends on the version used.

Quicksort has a space complexity of Θ(logn), even in the worst case, when it is carefully implemented such that

• in-place partitioning is used. This requires Θ(1).
• After partitioning, the partition with the fewest elements is (recursively) sorted first, requiring at most Θ(logn) space. Then the other partition is sorted using tail recursion or iteration. (This idea is commonly attributed to R.Sedgewick [1][2][3])

The version of quicksort with in-place partitioning uses only constant additional space before making any recursive call. However, if it has made Θ(logn) nested recursive calls, it needs to store a constant amount of information from each of them. Since the best case makes at most Θ(logn) nested recursive calls, it uses Θ(logn) space. The worst case makes Θ(n) nested recursive calls, and so needs Θ(n) space; Sedgewick's improved version using tail recursion requires Θ(logn) space in the worst case.

We are eliding a small detail here, however. If we consider sorting arbitrarily large lists, we have to keep in mind that our variables like left and right can no longer be considered to occupy constant space; it takes Θ(logn) bits to index into a list of n items. Because we have variables like this in every stack frame, in reality quicksort requires Θ((logn)2) bits of space in the best and average case and Θ(nlogn) space in the worst case. This isn't too terrible, though, since if the list contains mostly distinct elements, the list itself will also occupy Θ(nlogn) bits of space.

The not-in-place version of quicksort uses Θ(n) space before it even makes any recursive calls. In the best case its space is still limited to Θ(n), because each level of the recursion uses half as much space as the last, and

$\sum_{i=0}^{\infty} \frac{n}{2^i} = 2n.$

Its worst case is dismal, requiring

$\sum_{i=0}^n (n-i+1) = O(n^2)$

space, far more than the list itself. If the list elements are not themselves constant size, the problem grows even larger; for example, if most of the list elements are distinct, each would require about ΘO(logn) bits, leading to a best-case Θ(nlogn) and worst-case Θ(n2logn) space requirement.

## Selection-based pivoting

A selection algorithm chooses the kth smallest of a list of numbers; this is an easier problem in general than sorting. One simple but effective selection algorithm works nearly in the same manner as quicksort, except that instead of making recursive calls on both sublists, it only makes a single tail-recursive call on the sublist which contains the desired element. This small change lowers the average complexity to linear or Θ(n) time, and makes it an in-place algorithm. A variation on this algorithm brings the worst-case time down to Θ(n) (see selection algorithm for more information).

Conversely, once we know a worst-case Θ(n) selection algorithm is available, we can use it to find the ideal pivot (the median) at every step of quicksort, producing a variant with worst-case Θ(nlogn) running time. In practical implementations, however, this variant is considerably slower on average.

Another variant is to choose the Median of Medians as the pivot element instead of the median itself for partitioning the elements. While maintaining the asymptotically optimal run time complexity of Θ(nlogn) (by preventing worst case partitions), it is also considerably faster than the variant that chooses the median as pivot.

The C implementation of the above algorithm:

//Quicksort the array
void quicksort(int* array, int left, int right)
{
if(left >= right)
return;

int index = partition(array, left, right);
quicksort(array, left, index - 1);
quicksort(array, index + 1, right);
}

//Partition the array into two halves and return the
//index about which the array is partitioned
int partition(int* array, int left, int right)
{
//Makes the leftmost element a good pivot,
//specifically the median of medians
findMedianOfMedians(array, left, right);
int pivotIndex = left, pivotValue = array[pivotIndex], index = left, i;

swap(array, pivotIndex, right);
for(i = left; i < right; i++)
{
if(array[i] < pivotValue)
{
swap(array, i, index);
index += 1;
}
}
swap(array, right, index);

return index;
}

//Computes the median of each group of 5 elements and stores
//it as the first element of the group. Recursively does this
//till there is only one group and hence only one Median
int findMedianOfMedians(int* array, int left, int right)
{
if(left == right)
return array[left];

int i, shift = 1;
while(shift <= (right - left))
{
for(i = left; i <= right; i+=shift*5)
{
int endIndex = (i + shift*5 - 1 < right) ? i + shift*5 - 1 : right;
int medianIndex = findMedianIndex(array, i, endIndex, shift);

swap(array, i, medianIndex);
}
shift *= 5;
}

return array[left];
}

//Find the index of the Median of the elements
//of array that occur at every "shift" positions.
int findMedianIndex(int* array, int left, int right, int shift)
{
int i, groups = (right - left)/shift + 1, k = left + groups/2*shift;
for(i = left; i <= k; i+= shift)
{
int minIndex = i, minValue = array[minIndex], j;
for(j = i; j <= right; j+=shift)
if(array[j] < minValue)
{
minIndex = j;
minValue = array[minIndex];
}
swap(array, i, minIndex);
}

return k;
}

//Swap integer values by array indexes
void swap(int * array, int a, int b)
{
array[a] -= array[b];
array[b] += array[a];
array[a] = array[b] - array[a];
}


## Variants

There are three variants of quicksort that are worth mentioning:

• Balanced quicksort: choose a pivot likely to represent the middle of the values to be sorted, and then follow the regular quicksort algorithm.
• External quicksort: The same as regular quicksort except the pivot is replaced by a buffer. First, read the M/2 first and last elements into the buffer and sort them. Read the next element from the beginning or end to balance writing. If the next element is less than the least of the buffer, write it to available space at the beginning. If greater than the greatest, write it to the end. Otherwise write the greatest or least of the buffer, and put the next element in the buffer. Keep the maximum lower and minimum upper keys written to avoid resorting middle elements that are in order. When done, write the buffer. Recursively sort the smaller partition, and loop to sort the remaining partition.
• Three-way radix quicksort (also called multikey quicksort): is a combination of radix sort and quicksort. Pick an element from the array (the pivot) and consider the first character (key) of the string (multikey). Partition the remaining elements into three sets: those whose corresponding character is less than, equal to, and greater than the pivot's character. Recursively sort the "less than" and "greater than" partitions on the same character. Recursively sort the "equal to" partition by the next character (key).

## Comparison with other sorting algorithms

Quicksort is a space-optimized version of the binary tree sort. Instead of inserting items sequentially into an explicit tree, quicksort organizes them concurrently into a tree that is implied by the recursive calls. The algorithms make exactly the same comparisons, but in a different order.

The most direct competitor of quicksort is heapsort. Heapsort is typically somewhat slower than quicksort, but the worst-case running time is always Θ(nlogn). Quicksort is usually faster, though there remains the chance of worst case performance except in the introsort variant. If it's known in advance that heapsort is going to be necessary, using it directly will be faster than waiting for introsort to switch to it.

Quicksort also competes with mergesort, another recursive sort algorithm but with the benefit of worst-case Θ(nlogn) running time. Mergesort is a stable sort, unlike quicksort and heapsort, and can be easily adapted to operate on linked lists and very large lists stored on slow-to-access media such as disk storage or network attached storage. Although quicksort can be written to operate on linked lists, it will often suffer from poor pivot choices without random access. The main disadvantage of mergesort is that, when operating on arrays, it requires Θ(n) auxiliary space in the best case, whereas the variant of quicksort with in-place partitioning and tail recursion uses only Θ(logn) space. (Note that when operating on linked lists, mergesort only requires a small, constant amount of auxiliary storage.)

Bucket sort with two buckets is very similar to quicksort; the pivot in this case is effectively the value in the middle of the value range, which does well on average for uniformly distributed inputs.

## Notes

1. ^ "An Interview with C.A.R. Hoare". Communications of the ACM, March 2009.
2. ^ R.Miller, L.Boxer, Algorithms Sequential & Parallel, A Unified Approach, Prentice Hall, NJ, 2006
3. ^ David M. W. Powers, Parallelized Quicksort with Optimal Speedup, Proceedings of International Conference on Parallel Computing Technologies. Novosibirsk. 1991.
4. ^ M. D. McIlroy. A Killer Adversary for Quicksort. Software Practice and Experience: vol.29, no.4, 341–344. 1999. At Citeseer

## References

• Brian C. Dean, "A Simple Expected Running Time Analysis for Randomized 'Divide and Conquer' Algorithms." Discrete Applied Mathematics 154(1): 1-5. 2006.
• Hoare, C. A. R. "Partition: Algorithm 63," "Quicksort: Algorithm 64," and "Find: Algorithm 65." Comm. ACM 4(7), 321-322, 1961
• Hoare, C. A. R. "Quicksort." Computer Journal 5 (1): 10-15. (1962). (Reprinted in Hoare and Jones: Essays in computing science, 1989.)
• R. Sedgewick. Implementing quicksort programs, Comm. ACM, 21(10):847-857, 1978.
• David Musser. Introspective Sorting and Selection Algorithms, Software Practice and Experience vol 27, number 8, pages 983-993, 1997
• Donald Knuth. The Art of Computer Programming, Volume 3: Sorting and Searching, Third Edition. Addison-Wesley, 1997. ISBN 0-201-89685-0. Pages 113–122 of section 5.2.2: Sorting by Exchanging.
• Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. Introduction to Algorithms, Second Edition. MIT Press and McGraw-Hill, 2001. ISBN 0-262-03293-7. Chapter 7: Quicksort, pp.145–164.
• A. LaMarca and R. E. Ladner. "The Influence of Caches on the Performance of Sorting." Proceedings of the Eighth Annual ACM-SIAM Symposium on Discrete Algorithms, 1997. pp. 370-379.
• Faron Moller. Analysis of Quicksort. CS 332: Designing Algorithms. Department of Computer Science, Swansea University.
• Conrado Martínez and Salvador Roura, Optimal sampling strategies in quicksort and quickselect. SIAM J. Computing 31(3):683-705, 2001.
• Jon L. Bentley and M. Douglas McIlroy, Engineering a Sort Function, Software—Practice and Experience, Vol. 23(11), 1249–1265, 1993