Quicksort
3268249
226076130
2008-07-16T18:47:53Z
Jnoring
3226326
/* Algorithm */
{{redirect3|Q sort|For the psychological research method, see [[Q methodology]]}}
{{Infobox Algorithm
|class=[[Sorting algorithm]]
|image=[[Image:Sorting quicksort anim.gif|Quicksort in action on a list of numbers. The horizontal lines are pivot values.]]<small>Quicksort in action on a list of numbers. The horizontal lines are pivot values.</small>
|data=Varies
|time=<math>O(n\log n)</math> on average
|space=Varies by implementation
|optimal=Sometimes
|Stability=[Sorting_algorithm#Classification|Not Stable]
}}
'''Quicksort''' is a well-known [[sorting algorithm]] developed by [[C. A. R. Hoare]] that, [[average performance|on average]], makes <math>O(n\log n)</math> ([[big O notation]]) comparisons to sort ''n'' items. However, in the [[Best, worst and average case|worst case]], it makes <math>\Theta(n^2)</math> comparisons. Typically, quicksort is significantly faster in practice than other <math>\Theta(n \log n)</math> 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 [[Sorting algorithm#Classification|stable sort]].
== History ==
The quicksort algorithm was developed by Hoare in 1960 while working for the small British scientific computer manufacturer [[Elliott Brothers (computer_company)|Elliott Brothers]].<ref>{{cite web |url=http://www.computerhistory.org/timeline/?year=1960 |title=Timeline of Computer History: 1960 |publisher=Computer History Museum}}</ref>
== Algorithm ==
Quicksort sorts by employing a [[divide and conquer algorithm|divide and conquer]] strategy to divide a [[List (computing)|list]] into two sub-lists.
The steps are:
# Pick an element, called a [[Pivot element|''pivot'']], from the list.
# 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.
# [[Recursion (computer science)|Recursively]] sort the sub-list of lesser elements and the sub-list of greater elements.
The [[Base case#Recursive programming|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:
'''function''' quicksort(array)
'''var''' ''list'' less, greater
'''if''' length(array) ≤ 1
'''return''' array
select 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 (considering 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.
[[Image:Partition example.svg|right|200px|thumb|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.]]
The disadvantage of the simple version above is that it requires <math>\Omega(n)</math> extra storage space, which is as bad as [[mergesort]]. The additional memory allocations required can also drastically impact speed and cache performance in practical implementations. There is a more complicated version which uses an [[in-place]] partition algorithm and can achieve the complete sort using <math>O(n\log n)</math> space use on average:
<!-- NOTE: Please read carefully before editing, as this code has been verified as correct -->
'''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
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 <code>a[pivotIndex]</code> 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:
<!-- NOTE: Please read carefully before editing, as this code has been verified as correct -->
'''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 [[mergesort]], quicksort can also be easily [[parallel algorithm|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 <math>p</math> processors, we can divide a list of <math>n</math> elements into <math>p</math> sublists in <math>\Theta(n)</math> average time, then sort each of these in <math>\Theta\left(\frac{n}{p} \log\frac{n}{p}\right)</math>
average time. Ignoring the <math>\Theta(n)</math> preprocessing, this is [[linear speedup]]. Given <math>n</math> processors, only <math>\Theta(n)</math> 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<ref>R.Miller, L.Boxer, Algorithms Sequential & Parallel, A Unified Approach, Prentice Hall, NJ, 2006</ref>. For example, in 1991 David Powers described a parallelized quicksort that can operate in <math>O(\log n)</math> time given enough processors by performing partitioning implicitly<ref>David M. W. Powers, [http://citeseer.ist.psu.edu/327487.html Parallelized Quicksort with Optimal Speedup], ''Proceedings of International Conference on Parallel Computing Technologies''. [[Novosibirsk]]. 1991.</ref>.
== Formal analysis ==
From the initial description it's not obvious that quicksort takes <math>\Theta(n \log n)</math> time on average. It's not hard to see that the partition operation, which simply loops over the elements of the array once, uses <math>\Theta(n)</math> time. In versions that perform concatenation, this operation is also <math>\Theta(n)</math>.
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 <math>\log n</math> nested calls before we reach a list of size 1. This means that the depth of the [[Call stack|call tree]] is <math>\Theta(\log n)</math>. 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 <math>\Theta(n)</math> time all together (each call has some constant overhead, but since there are only <math>\Theta(n)</math> calls at each level, this is subsumed in the <math>\Theta(n)</math> factor). The result is that the algorithm uses only <math>\Theta(n \log n)</math> time.
An alternate approach is to set up a [[recurrence relation]] for the <math>T(n)</math> factor, the time needed to sort a list of size <math>n</math>. Because a single quicksort call involves <math>\Theta(n)</math> factor work plus two recursive calls on lists of size <math>n/2</math> in the best case, the relation would be:
:<math>T(n) = \Theta(n) + 2T\left(\frac{n}{2}\right).</math>
The [[master theorem]] tells us that <math>T(n) = \Theta(n \log n)</math>.
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 <math>100 log n</math>, so the total running time is still <math>\Theta(n \log n)</math>.
In the worst case, however, the two sublists have size 1 and <math>n-1</math> (for example, if the array consists of the same element by value), and the call tree becomes a linear chain of <math>n</math> nested calls. The <math>i</math>th call does <math>\Theta(n-i)</math> work, and <math>\sum_{i=0}^n (n-i) = \Theta(n^2)</math>. The recurrence relation is:
:<math>T(n) = \Theta(n) + T(1) + T(n-1) = O(n) + T(n-1)</math>
This is the same relation as for [[insertion sort]] and [[selection sort]], and it solves to <math>T(n) = \Theta(n^2)</math>.
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.<ref>M. D. McIlroy. A Killer Adversary for Quicksort. Software Practice and Experience: vol.29, no.4, 341–344. 1999. [http://citeseer.ist.psu.edu/212772.html At Citeseer]</ref>
=== Randomized quicksort expected complexity ===
Randomized quicksort has the desirable property that it requires only <math>\Theta(n \log n)</math> [[expected value|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 <math>2 \log_2 n</math> times before reaching lists of size 1, yielding an <math>\Theta(n \log n)</math> 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 <math>k</math> heads. Although this could take a long time, on average only <math>2k</math> flips are required, and the chance that you won't get <math>k</math> heads after <math>100k</math> flips is infinitesimally small. By the same argument, quicksort's recursion will terminate on average at a call depth of only <math>2(2\log_2 n)</math>. But if its average call depth is <math>\Theta(\log n)</math>, and each level of the call tree processes at most <math>n</math> elements, the total amount of work done on average is the product, <math>\Theta(n \log n)</math>.
=== Average complexity ===
Even if pivots aren't chosen randomly, quicksort still requires only <math>\Theta(n \log n)</math> 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 <math>n</math> 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:
:<math>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.</math>
Here, <math>n-1</math> 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.
<math>
\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}
</math>
=== Space complexity ===
The space used by quicksort depends on the version used.
Quicksort has a space complexity of <math>\Theta(\log n)</math>, even in the worst case, when it is carefully implemented such that
* in-place partitioning is used. This requires <math>\Theta(1)</math>.
* After partitioning, the partition with the fewest elements is (recursively) sorted first, requiring at most <math>\Theta(\log n)</math> space. Then the other partition is sorted using tail-recursion or iteration. (This idea is commonly attributed to R.Sedgewick [http://www.cs.columbia.edu/~hgs/teaching/isp/hw/qsort.c ][http://www.ugrad.cs.ubc.ca/~cs260/chnotes/ch6/Ch6CovCompiled.html ][http://home.tiscalinet.ch/t_wolf/tw/ada95/sorting/index.html ])
<!-- please replace these random links with a good reference to Sedgewick ... or perhaps Knuth quoting Sedgewick -->
The version of quicksort with in-place partitioning uses only constant additional space before making any recursive call. However, if it has made <math>\Theta(\log n)</math> nested recursive calls, it needs to store a constant amount of information from each of them. Since the best case makes at most <math>\Theta(\log n)</math> nested recursive calls, it uses <math>\Theta(\log n)</math> space. The worst case makes <math>\Theta(n)</math> nested recursive calls, and so needs <math>\Theta(n)</math> space.
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 <math>\Theta(\log n)</math> bits to index into a list of <math>n</math> items. Because we have variables like this in every stack frame, in reality quicksort requires <math>\Theta(\log^2n)</math> bits of space in the best and average case and <math>\Theta(n \log n)</math> 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 <math>\Theta(n \log n)</math> bits of space.
The not-in-place version of quicksort uses <math>\Theta(n)</math> space before it even makes any recursive calls. In the best case its space is still limited to <math>\Theta(n)</math>, because each level of the recursion uses half as much space as the last, and
:<math>\sum_{i=0}^{\infty} \frac{n}{2^i} = 2n.</math>
Its worst case is dismal, requiring
:<math>\sum_{i=0}^n (n-i+1) = O(n^2)</math>
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 <math>\Theta{O}(\log n)</math> bits, leading to a best-case <math>\Theta(n \log n)</math> and worst-case <math>\Theta(n^2 \log n)</math> space requirement.
== Selection-based pivoting ==
A [[selection algorithm]] chooses the ''k''th 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 <math>\Theta(n)</math> time, and makes it an [[in-place algorithm]]. A variation on this algorithm brings the worst-case time down to <math>\Theta(n)</math> (see [[selection algorithm]] for more information).
Conversely, once we know a worst-case <math>\Theta(n)</math> 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 <math>\Theta(n \log n)</math> running time. In practical implementations, however, this variant is considerably slower on average.
== 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 <math>\Theta(n \log n)</math>. 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. Heapsort also has the important advantage of using only constant additional space (heapsort is in-place), whereas even the best variant of quicksort uses <math>\Theta(\log n)</math> space. However, heapsort requires efficient random access to be practical.
Quicksort also competes with [[mergesort]], another recursive sort algorithm but with the benefit of worst-case <math>\Theta(n \log n)</math> running time. Mergesort is a [[stable sort]], unlike quicksort and heapsort, and can be easily adapted to operate on [[linked list]]s 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 <math>\Theta(n)</math> auxiliary space in the best case, whereas the variant of quicksort with in-place partitioning and tail recursion uses only <math>\Theta(\log n)</math> 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 ==
<references/>
==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. [http://dx.doi.org/10.1093/comjnl/5.1.10 "Quicksort."] Computer Journal 5 (1): 10-15. (1962). (Reprinted in Hoare and Jones: [http://portal.acm.org/citation.cfm?id=SERIES11430.63445 ''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]]. [http://www.cs.swan.ac.uk/~csfm/Courses/CS_332/quicksort.pdf Analysis of Quicksort]. CS 332: Designing Algorithms. Department of Computer Science, University of Wales Swansea.
* Steven Skiena. [http://www.cs.sunysb.edu/~algorith/lectures-good/node5.html Lecture 5 - quicksort]. CSE 373/548 - Analysis of Algorithms. Department of Computer Science. [[State University of New York at Stony Brook]].
* 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, [http://citeseer.ist.psu.edu/bentley93engineering.html Engineering a Sort Function], ''Software—Practice and Experience'', Vol. 23(11), 1249–1265, 1993
== See also ==
* [[Introsort]]
* [[Flashsort]]
==External links==
{{Wikibooks|Algorithm implementation|Sorting/Quicksort|Quicksort}}
* [http://tide4javascript.com/?s=Quicksort Analyze Quicksort in an online Javascript IDE]
* [http://thomasgilray.com/classes/quicksort.php Javascript Quicksort and Bubblesort]
* [http://www.atkinson.yorku.ca/~sychen/research/sorting/sortingHome.html Quicksort applet] with "level-order" recursive calls to help improve algorithm analysis
* [http://www.wanginator.de/studium/applets/quicksort_en.html Quicksort Java Applet]
* [http://fiehnlab.ucdavis.edu/staff/wohlgemuth/java/quicksort Multidimensional quicksort in Java]
* [http://en.literateprograms.org/Category:Quicksort Literate implementations of Quicksort in various languages] on LiteratePrograms
* [http://www.mycsresource.net/articles/programming/sorting_algos/quicksort/ Quicksort tutorial with illustrated examples]
* [http://vision.bc.edu/~dmartin/teaching/sorting/anim-html/quick.html A graphical demonstration and discussion of 2-way partition quick sort]
* [http://vision.bc.edu/~dmartin/teaching/sorting/anim-html/quick3.html A graphical demonstration and discussion of 3-way partition quick sort]
* [http://coderaptors.com/?QuickSort A colored graphical Java applet] which allows experimentation with initial state and shows statistics
{{sorting}}
[[Category:Sorting algorithms]]
[[Category:Comparison sorts]]
[[Category:Articles with example pseudocode]]
[[ar:ترتيب سريع]]
[[bn:কুইক সর্ট]]
[[bg:Бързо сортиране]]
[[ca:Quicksort]]
[[cs:Quicksort]]
[[de:Quicksort]]
[[es:Quicksort]]
[[fa:کوییکسورت]]
[[fr:Tri rapide]]
[[ko:퀵 정렬]]
[[is:Snarröðun]]
[[it:Quicksort]]
[[he:מיון מהיר]]
[[lt:Greitojo rikiavimo algoritmas]]
[[hu:Gyorsrendezés]]
[[nl:Quicksort]]
[[ja:クイックソート]]
[[no:Quicksort]]
[[uz:Quicksort]]
[[pl:Sortowanie szybkie]]
[[pt:Quicksort]]
[[ru:Быстрая сортировка]]
[[sk:Quicksort]]
[[sl:Hitro urejanje]]
[[fi:Pikalajittelu]]
[[sv:Quicksort]]
[[vi:Sắp xếp nhanh]]
[[tr:Hızlı sıralama]]
[[uk:Швидке сортування]]
[[zh:快速排序]]