quick sort analysis

13
Analysis Quick-sort of

Upload: avinash-sharma

Post on 01-Oct-2015

232 views

Category:

Documents


2 download

DESCRIPTION

Quick Sort Analysis

TRANSCRIPT

PowerPoint Presentation

AnalysisQuick-sortofWORST-CASE ANALYSISIn worst-case partitioning (unbalanced): T(n) = T(n-1) + T(0) + (n)

Running time, T(n) = (n2)WORST-CASE ANALYSIS

A recursion tree for QUICKSORT in which the partition procedure always puts only a single element on one side of the partition: The substitution method for solving recurrences comprises two steps:1. Guess the form of the solution.2. Use mathematical induction to find the constants and show that the solution works.WORST-CASE ANALYSISWe can use the substitution method to establish either upper or lower bounds on a recurrence.Using substitution method, we can show that the running time of quicksort is O(n2).WORST-CASE ANALYSISLet T(n) be worst-case time of an input size nWe have the recurrenceT(n) = max (T(q) + T(n-q-1)) + (n) 0 q n-1WORST-CASE ANALYSISGuess that T(n) = O(n2) The substitution method requires us to prove that : T(n) = cn2for constant c > 0.Induction hypothesis: T(k) ck2 for any k < nYielding T(q) + T(n-q-1) cq2 + c(n-q-1)2Substituting into the recurrence, we getT(n) max (cq2 + c(n-q-1)2) + (n) 0 q n-1= c max (q2 + (n-q-1)2) + (n) 0 q n-1WORST-CASE ANALYSIST(n) c max (q2 + (n-q-1)2) + (n) 0 q n-1

The expression q2 + (n-q-1)2 achieves a maximum over the range 0 q n-1 at one of the endpoints since we can pick the constant c large enough so that the c(2n-1) term dominates the (n) term.

Thus, T(n) = O(n2) T(n) cn2 c(2n-1) + (n) cn2RANDOMIZED VERSION OF QUICKSORTRANDOMIZED-PARTITION(A, p, r)1 i = RANDOM(p, r)2 exchange A[r] with A[i]3 return PARTITION(A, p, r)RANDOMIZED-QUICKSORT(A, p, r)1 if p < r2 q = RANDOMIZED-PARTITION(A, p, r)3 RANDOMIZED-QUICKSORT(A, p, q 1)4 RANDOMIZED-QUICKSORT(A, q + 1, r)PARTITION(A, p, r)1 x = A[r]2 i = p - 13 for j = p to r - 14 if A[j] x5 i = i + 16 exchange A[i] with A[j] 7 exchange A[i + 1] with A[r]8 return i + 18EXPECTED RUNNING TIMERunning time and comparisonsFor ease of analysis, we rename the elements of the array A as z1,z2 ,.,zn , with zi being the i-th smallest element. We also define the set Zij = { zi,zi+1,..,zj } to be the set of elements between zi and zj , inclusive.Our analysis uses indicator random variables. We defineXij = I {zi is compared to zj}

9EXPECTED RUNNING TIMETotal no. of comparisons performed by algorithm :Taking expectations of both sides,It remains to compute Pr {zi is compared to zj}110EXPECTED RUNNING TIMEPr {zi is compared to zj} = Pr {zi or zj is first pivot chosen from Zij}= Pr {zi is first pivot chosen from Zij} + Pr {zj is first pivot chosen from Zij}

211EXPECTED RUNNING TIMECombining equations and ,we get12For k = j i,1212Presented By:Sahil Arora 133137Avinash Sharma 133213