11.07.2015 Views

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

240 Chap. 7 Internal Sorting72 6 57 88 60 42 83 73 48 85Pivot = 6048 6 57 42 60 88 83 73 72 85Pivot = 6 Pivot = 736 42 57 4872 73 85 88 83Pivot = 57Pivot = 88Pivot = 42 42 48 5785 83 88 Pivot = 8542 4883856 42 48 57 60 72 73 83 85 88Final Sorted ArrayFigure 7.14 An illustr<strong>at</strong>ion of Quicksort.how much work is done by the nested while loops. The do loop as a whole isguaranteed to move both l <strong>and</strong> r inward <strong>at</strong> least one position on each first pass.Each while loop moves its variable <strong>at</strong> least once (except in the special case wherer is <strong>at</strong> the left edge of the array, but this can happen only once). Thus, we see th<strong>at</strong>the do loop can be executed <strong>at</strong> most s times, the total amount of work done movingl <strong>and</strong> r is s, <strong>and</strong> each while loop can fail its test <strong>at</strong> most s times. The total workfor the entire partition function is therefore Θ(s).Knowing the cost of findpivot <strong>and</strong> partition, we can determine thecost of Quicksort. We begin with a worst-case analysis. The worst case will occurwhen the pivot does a poor job of breaking the array, th<strong>at</strong> is, when there are noelements in one partition, <strong>and</strong> n − 1 elements in the other. In this case, the divide<strong>and</strong> conquer str<strong>at</strong>egy has done a poor job of dividing, so the conquer phase willwork on a subproblem only one less than the size of the original problem. If thishappens <strong>at</strong> each partition step, then the total cost of the algorithm will ben∑k = Θ(n 2 ).k=1In the worst case, Quicksort is Θ(n 2 ). This is terrible, no better than BubbleSort. 2 When will this worst case occur? Only when each pivot yields a bad partitioningof the array. If the pivot values are selected <strong>at</strong> r<strong>and</strong>om, then this is extremelyunlikely to happen. When selecting the middle position of the current subarray, it2 The worst insult th<strong>at</strong> I can think of for a sorting algorithm.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!