Tutorial 4
-
Upload
kylee-mccarthy -
Category
Documents
-
view
12 -
download
0
description
Transcript of Tutorial 4
Tutorial 4
The Quicksort Algorithm
QuickSort
Divide: Choose a pivot, P Form a subarray with all elements ≤ P Form a subarray with all elements > P
Conquer Call “divide” recursive call until there is all the su
barraies have one element only. Combine
Nothing to do because all elements have been sorted already after the “conquer” step.
Quicksort
Complexity of the Partition step: O(n). How to obtain?
Worst case partition has complexity O(n2). How to obtain?
Best case partition has complexity O(nlogn). How to obtain?
How about average case? Why we need the randomized version Q
uicksort?
Quicksort
Zij={zi, zi+1,zi+2,……,zj} Each pair of elements are compared eith
er 0 time or 1 time only. Why? Xij=I{zi compares with zj}, it can be 1 or 0. Total No. of comparison X
1
1 1
n
i
n
ijijXX
1
1 1
n
i
n
ijijXX
Expectation of X: Average number of comparisons for randomized Quicksort
1
1 1
1
1 1
)()(
)()(
n
i
n
ijij
n
i
n
ijij
XPXE
XEXEUsing the lemma for the Indicator function, it equals P(zi compares with zj).
QuickSort
P(Xij)=Prob of {(zi is pivot) U (zj is pivot)} P(Xij)=P(zi is pivot)+P(zj is pivot), why? P(Xij)=1/(j-i+1)+1/(j-i+1)
1
1 11
2)(n
i
n
ijijXE
Quicksort
What happens if all elements have the same values?
Good news or Bad news? What happens if all elements have
been sorted? Any ways to modify?
Original Quicksort Algorithm: Hoare-Partition
Hoare-Partition(A,p,r)
x ← A[p]; i ← p-1; j ← r+1
While true
do repeat j ← j-1
until A[j] ≤ x
do repeat i ← i+1
until A[i] x
if i < j
then exchange A[i], A[j]
else return j
True or False? Q1: The indices i and j have values such
that elements outside A[p..r] are not accessed.
Q2: When the procedure terminates, p≤ j < r.
Q3: elements of A[p..j] is less than or equal to elements of A[j+1..r].