Quicksort
Description of quicksort
Quicksort, like merge sort, applies the divide-and-conquer paradigm
The following procedure implements quicksort:
To sort an entire array A, the initial call is QUICKSORT(A,1,A.length)1
2
3
4
5QUICKSORT(A,p,r)
if p<r
q = PARTITION(A, P,r)
QUICKSORT(A, P,q-1)
QUICKSORT(A,q+1,r)The key to the algorithm is the PARTITION procedure
PARTITION always selects an element x = A[r]as a pivot element around which to partition the subarray A[p..r]1
2
3
4
5
6
7
8
9PARTITION(A, P,r)
x = A[r]
i=p-1
for j=p to r-1
if A[j] ≤ x
i=x+1
exchange A[i] with A[j]
exchange A[j+1] with A[r]
return i+1
Performance of quicksort
- The running time of quicksort depends on whether the partitioning is balanced or unbalanced, which in turn depends on which elements are used for partitioning.
- If the partitioning is balanced, the algorithm runs asymptotically as fast as merge sort. . If the partitioning is unbalanced, however, it can run asymptotically as slowly as insertion sort.
- Worst-case partitioning
- The worst-case behavior for quicksort occurs when the partitioning routine produces one subproblem with n-1 elements and one with 0 elements.
- use the substitution method to prove that the
recurrence has the solution
- Best-case partitioning
- In the most even possible split, PARTITION produces two subproblems, each of size no more than n/2.
- By case 2 of the master theorem, this recurrence
has the solution
- Balanced partitioning
- The average-case running time of quicksort is much closer to the best case than to the worst case.
- Intuitively,The running time is
A randomized version of quicksort
Instead of always using
1 | RANDOMIZED-PARTITION(A,p,r) |
1 | RANDOMIZED-QUICKSORT(A,p,r) |
Analysis of quicksort
Worst-case analysis
Let
Continuing with our bounding of
Expected running time
Lemma: Let
We first observe that each pair of elements is compared at most once. Elements are compared only to the pivot element and, after a particular call of PARTITION finishes, the pivot element used in that call is never again compared to any other elements.
We define the set
We define
Since each pair is compared at most once, we can easily characterize
the total number of comparisons performed by the algorithm: