Introduction of The Chapter
Quicksort algorithm has a worst-case running tine of Θ(n2) , and a expected running time of Θ(nlgn) .It runs in place and is not stable.
Description of quicksort
Quick sort applices the divide-and-conquer paradigm. The three steps of it show :
- Divide : Partition the array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[p], which is , in turn , less than or equal to eack element of A[q+1..r]. Compute the index q as part of this partition procedure.
- Conquer : Sort the two subarrays by recursive calls to quick sort
- Combine : Because the two subarrays are already sorted, no work is needed to combine them.
Quick-Sort (A, p, r)
if p < r
q = Partition (A, p, r)
Quick-Sort (A, p, q-1)
Quick-Sort (A, q+1,r)
Partition (A, p, r)
x = A[r]
i = p - 1
for j=p to r-1
if A[j] <= x
i = i+1
exchange A[i] with A[j]
exchange A[i+1] with A[r]
return i+1
The Partition has a running time of Θ(n) on the subarray A[p..r].
Performance of quick sort
Worst-case : The every call of Partition partition the array into a subarray with 0 element and n-1 elements. So the recurrence for running time is
T(n)=T(n−1)+T(0)+Θ(n)=Θ(n2)
The worst-case running time occurs when the input is already completely sorted.
Best-case : Partition produce two subproblems, each of size no more than n/2. So the recurrence for running time is
T(n)=2T(n/2)+Θ(n)=Θ(nlgn)
Average-case : The recurrence for running time is still O(nlgn) , but with a slightly larger constant hidden by the O -notation.
A randomized version of quicksort
Selecting randomly the chosen element from A[p..r] to be the pivot.
Randomized-Partition (A, p, r)
i = Random (p, r)
exchange A[r] with a[i]
return Partition (A, p, r)
Randomized-QuickSort (A, p, r)
if p < r
q = Randomized-Paritition (A, p, r)
Randomized-QuickSort (A, p, q-1)
Randomized-QuickSort (A, q+1, r)
Analysis of quicksort
Worst-case :
using the substitute model, we assume T(n)≤cn2 , and θ(n)=c0n .
T(n)≤cmax0≤q≤n−1(q2+(n−q