Tutorial 4 The Quicksort Algorithm Quick Sort Divide

  • Slides: 9
Download presentation
Tutorial 4 The Quicksort Algorithm

Tutorial 4 The Quicksort Algorithm

Quick. Sort ¡ Divide: l l l ¡ Conquer l ¡ Choose a pivot,

Quick. Sort ¡ Divide: l l l ¡ Conquer l ¡ Choose a pivot, P Form a subarray with all elements ≤ P Form a subarray with all elements > P Call “divide” recursive call until there is all the subarraies have one element only. Combine l 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

Quicksort Complexity of the Partition step: O(n). How to obtain? ¡ Worst case partition has complexity O(n 2). How to obtain? ¡ Best case partition has complexity O(nlogn). How to obtain? ¡ How about average case? ¡ Why we need the randomized version Quicksort? ¡

Quicksort ¡ ¡ Zij={zi, zi+1, zi+2, ……, zj} Each pair of elements are compared

Quicksort ¡ ¡ Zij={zi, zi+1, zi+2, ……, zj} Each pair of elements are compared either 0 time or 1 time only. Why? Xij=I{zi compares with zj}, it can be 1 or 0. Total No. of comparison X

Expectation of X: Average number of comparisons for randomized Quicksort Using the lemma for

Expectation of X: Average number of comparisons for randomized Quicksort Using the lemma for the Indicator function, it equals P(zi compares with zj).

Quick. Sort ¡ ¡ ¡ P(Xij)=Prob of {(zi is pivot) U (zj is pivot)}

Quick. Sort ¡ ¡ ¡ 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)

Quicksort What happens if all elements have the same values? ¡ Good news or

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(A, p, r) x ← A[p]; i ← p-1; j ←

Original Quicksort Algorithm: 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? ¡ Q 1: The indices i and j have values such

True or False? ¡ Q 1: The indices i and j have values such that elements outside A[p. . r] are not accessed. ¡ Q 2: When the procedure terminates, p≤ j < r. ¡ Q 3: elements of A[p. . j] is less than or equal to elements of A[j+1. . r].