Tutorial 4

9
Tutorial 4 The Quicksort Algorithm

description

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 subarraies have one element only. Combine - PowerPoint PPT Presentation

Transcript of Tutorial 4

Page 1: Tutorial 4

Tutorial 4

The Quicksort Algorithm

Page 2: Tutorial 4

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.

Page 3: Tutorial 4

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?

Page 4: Tutorial 4

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

Page 5: Tutorial 4

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).

Page 6: Tutorial 4

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

Page 7: Tutorial 4

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?

Page 8: Tutorial 4

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

Page 9: Tutorial 4

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].