4_quicksort

4_quicksort - Quicksort David Kauchak Quicksort...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Quicksort David Kauchak Quicksort Quicksort ( A,p,r ) 1 if p < r 2 q Partition ( A,p,r ) 3 Quicksort ( A,p,q - 1) 4 Quicksort ( A,q + 1 ,r ) Partition ( A,p,r ) 1 i p - 1 2 for j p to r - 1 3 if A [ j ] A [ r ] 4 i i + 1 5 swap A [ i ] and A [ j ] 6 swap A [ i + 1] and A [ r ] 7 return i + 1 Is it correct? Loop invariant: Elements in the subarray A [ p...i ] are all less than or equal to A [ r ] and elements in the subarray A [ i + 1 ...j - 1] are all greater than A [ r ] Proof by induction: Base case: i = p - 1, so A [ p...i ] is empty and j = p and i + 1 = p , so A [ i + 1 ...j - 1] is also empty. Inductive case: We’ll assume that the invariant is true for itera- tion j and show that iteration j + 1 is also true. There are two cases based on line the if statement in line 4. 1
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
1. If A [ j ] > A [ r ] the only thing that happenens is that j is incremented. This means that A [ p...i ] remains unchanged and will still contain elements that are less than or equal to A [ r ]. A [ i +1 ...j ] will consist of A [ i +1 ...j - 1], which contains elements greater than A [ r ] (by induction), and one additionaly element A [ j ] which we know is greater than A [ r ], so we know the entire subarray A [ i +1 ...j ] contains elements that are greater than A [ r ]. 2. If A [ j ] A [ r ] then two things happen. i is incremented and A [ i ] is swapped with A [ j ]. A [ p...i ] will then contain the elements A [ p...i - 1], which we already know are less than or equal to A [ r ], and element A [ j ], which is also less than or equal to A [ r ]. Sub- array A [ i + 1 ...j ] will contain the same elements, except the last element, A [ j ], will be the old Frst element, A [ i +1], and the other elements will be shifted down. At termination, what does this tell us about the Partition pro- cedure? If Parition is correct, is Quicksort correct? Running time? What is the running time of
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 8

4_quicksort - Quicksort David Kauchak Quicksort...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online