1 / 9

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

Télécharger la présentation

Tutorial 4

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Tutorial 4 The Quicksort Algorithm

  2. 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 • Nothing to do because all elements have been sorted already after the “conquer” step.

  3. 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 Quicksort?

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

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

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

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

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

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

More Related