Download presentation
Presentation is loading. Please wait.
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(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?
4
Quicksort Zij={z i, z i+1,z i+2, ……,z j } Each pair of elements are compared either 0 time or 1 time only. Why? Xij=I{z i compares with z j }, 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(X ij )=Prob of {(zi is pivot) U (zj is pivot)} P(X ij )=P(zi is pivot)+P(zj is pivot), why? P(X ij )=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].
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.