-Divide and conquer
-Sorts "in place"
-Very practical(with turning)
...(≤x)x...(>x) linear-time-->Θ(n)
Example:
6 10 13 5 8 3 2 11,Key=6
i j
6 5 13 10 8 3 2 11,5<key,第一個比key=6小的數是5,交換i+1位置上的10與5的位置,得到新的序列,並且是j指向5的下一個位置
i j
6 5 3 10 8 13 2 11,和上一步類似
i j
6 5 3 2 8 13 10 11,
i j
2 5 3 6 8 13 10 11
這樣就把序列分爲了<key,=key,>key的三部分
下面給出Quicksort的僞代碼:
Quicksort(A,p,q)
if p<q
then r<--Partition(A,p,q)
Quicksort(A,p,r-1)
Quicksort(A,r-1,q)
Init.call QuickSort(A,1,n)
Analysisi:assume all elements are different
Worst-case:
-Input sorted or reverse sorted
-one of partition has no elements
T(n)=T(0)+T(n-1)+Θ(n)=Θ(n^2)
Best-case:
If we are really lucky,Partition splits the array n/2:n/2
T(n)=2T(n/2)+Θ(n)=Θ(nlgn)
Suppose split is always 1/10:9/10
T(n)=T(n/10)+T(9n/10)+Θ(n)=Θ(nlgn)
Suppose we alternate lucky,unlucky,lucky,unlucky,...
L(n)=2L(n/2)+Θ(n) lucky
L(n)=L(n-1)+Θ(n) unlucky
then L(n)=2[L(n/2-1)+Θ(n)]+Θ(n)=Θ(nlgn) (由主定理可得)
Randomized quicksort (隨機化快速排序):
-running time is independent of the input ordering
-no assumptions about the input distribution
-no specific input elicit the worst-case behavior
-the worst-case is determined only by a random-number generator
Analysis:Pivot on random element
T(n)=r.|v. for running time assuming rand number's independent.
For k=0,1,...,n-1,let
xk=1,if partition generates k:n-k-1 split
xk=0,otherwise
xk作爲指示器變量,E(xk)=1/n
T(n)=∑xk[T(k)+T(n-k-1)+Θ(n)]
E[T(n)]=2/n∑T(k)+Θ(n)
Absorb k=0,1 terms into Θ(n) for conventience
Prove E[T(n)]≤anlgn for const a>0
Choose a bigenough so that anlgn≥E[T(n)] for small n
use fact ∑klgk≤1/2n^2lgn-1/8n^2(數學歸納可證明)
可得E[T(n)]=Θ(nlgn)
通常Quicksort要比歸併法快3倍以上。