4 Randquicksort
4 Randquicksort
CSOR W4246
Eleni Drinea
Computer Science Department
Columbia University
Randomized quicksort
Outline
1 Randomized Quicksort
Today
1 Randomized Quicksort
Pseudocode for randomized Quicksort
O(n + X).
O(n + X).
Fact 1.
Fix any two input items. During the execution of the algorithm,
they may be compared at most once.
Towards a bound for T (n)
O(n + X).
Fact 1.
Fix any two input items. During the execution of the algorithm,
they may be compared at most once.
Proof.
Comparisons are only performed with the pivot of each Partition
call. After Partiton returns, pivot is in its final location in the output
and will not be part of the input to any future recursive call.
Simplifying the analysis
n(n−1)
There are n numbers in the input, hence n2 =
I
2
distinct (unordered) pairs of input numbers.
n
I From Fact 1, the algorithm will perform at most 2
comparisons.
I What is the expected number of comparisons?
Simplifying the analysis
n(n−1)
There are n numbers in the input, hence n2 =
I
2
distinct (unordered) pairs of input numbers.
n
I From Fact 1, the algorithm will perform at most 2
comparisons.
I What is the expected number of comparisons?
Goal: compute Pr[Xij = 1], that is, the probability that two
fixed items zi and zj are ever compared.
Fix two items zi and zj . When are they compared?
z₁ < z₂ < … < zᵢ < zᵢ₊₁ < … !"""z!"" < … < zk < … < zn !!
1. pivot = zi
2. pivot = zj
1. pivot = zi
2. pivot = zj
X n−i+1
n−1 X 1
= 2 (3)
`
i=1 `=2
k
P 1
Note that ` = Hk is the k-th harmonic number, such that
`=1
ln k ≤ Hk ≤ ln k + 1 (4)
n−i+1
P 1
Hence ` ≤ ln (n − i + 1). Substituting in (3), we get
`=2
n−1
X n−1
X
E[X] ≤ 2 ln (n − i + 1) ≤ 2 ln n = O(n ln n)
i=1 i=1
From E[X] to T (n)
T (n) = Θ(n ln n)