Quicksort-2:快速排序-2
Animation
Animated visualization of the quicksort algorithm. The horizontal lines are pivot values.
Full example of quicksort on a random set of numbers. The shaded element is the pivot. It is always chosen as the last element of the partition. However, always choosing the last element in the partition as the pivot in this way results in poor performance ( O(n2) ) on already sorted arrays, or arrays of identical elements. Since sub-arrays of sorted / identical elements crop up a lot towards the end of a sorting procedure on a large set, versions of the quicksort algorithm which choose the pivot as the middle element run much more quickly than the algorithm described in this diagram on large sets of numbers.
Complexity
Class | Sorting algorithm |
---|---|
Data structure | Array |
Worst case performance | O(n2) |
Best case performance | O(nlogn) (simple partition) or O(n) (three-way partition and equal keys) |
Average case performance | O(nlogn) |
Worst case space complexity | O(n) auxiliary (naive), O(logn) auxiliary (Sedgewick 1978) |
Algorithm Q
Algorithm Q (Quicksort). Records R1,...,RN are rearranged in place; after
sorting is complete their keys will be in order, K1<=...<=KN . An auxiliary
stack with at most ⌊lgN⌋ entries is needed for temporary storage. This algorithm
follows the quicksort partitioning procedure described in the text above, with
slight modifications for extra efficiency:
a) We assume the presence of artificial keys K0=−∞ and KN+1=+∞ such
that
K0<=Ki<=KN+1 for 1<=i<=N . (13)
(Equality is allowed.)
b) Subfiles of M or fewer elements are left unsorted until the very end of the
procedure; then a single pass of straight insertion is used to produce the final
ordering. Here
the text below. (This idea, due to R. Sedgewick, saves some of the overhead
that would be necessary if we applied straight insertion directly to each small
subfile, unless locality of reference is significant.)
c) Records with equal keys are exchanged, although it is not strictly necessary
to do so. (This idea, due to R. C. Singleton, keeps the inner loops fast and
helps to split subfiles nearly in half when equal elements are present; see
exercise 18.)
Q1. [Initialize.] If N<