C++02類與物件
阿新 • • 發佈:2020-12-07
快速排序
皮卡,皮卡,十萬伏特!!!
最壞時間複雜度:O( n 2 n^2 n2)
期望時間複雜度O( n l g n nlgn nlgn),且常數因子很小
快速排序-基本版本
- QUICKSORT(A,p,r)
if p < r
q = PARTITION(A,p,r)
QUICKSORT(A,p,q-1)
QUICKSORT(A,q+1,r)
對陣列進行全排:QUICKSORT(A,1,A.length)
- 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
快速排序-隨機化版本
- 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-PARTITION(A,p,r)
RANDOMIZED-QUICKSORT (A,p,q-1)
RANDOMIZED-QUICKSORT(A,q+1,r)