Quick Sort: Characteristics
Quick Sort: Characteristics
Quick Sort: Characteristics
Characteristics
sorts
Partitioning
Linear
Partition(A,p,r)
01
02
03
04
05
06
07
08
09
10
11
j j
i i
xA[r]
17 12
ip-1
X=10
i
jr+1
while TRUE
10 12
repeat jj-1
until A[j] x
repeat ii+1
until A[i] x
10 5
if i<j
then exchange A[i]A[j]
else return j
10
19 23
10
j
6
19 23
19 23
17
12 17
23 19 12 17
3
Quicksort(A,p,r)
01 if p<r
02
then q Partition(A,p,r)
03
Quicksort(A,p,q)
04
Quicksort(A,q+1,r)
Analysis of Quicksort
Assume
Best Case
T (n) = 2T (n / 2) + (n)
Worst Case
What
( k )
k =1
= ( k )
k =1
= ( n 2 )
7
input
is sorted
input reverse sorted
Same
Analysis of Quicksort
Suppose
10
11
Suppose, we alternate
lucky and unlucky
cases to get an
average behavior
(n)
n-1
1
(n-1)/2
(n-1)/2
(n-1)/2+1
( n )
(n-1)/2
12
Randomized algorithm
running time is independent of the input ordering
no specific input triggers worst-case behavior
the worst-case is only determined by the output of the
random-number generator
13
Randomized Quicksort
Assume
15
16
O(n2)
Best case running time of quicksort is
O(nlog2 n)
Expected running time of quicksort is
O(nlog2 n)
18
19
20