template class i temtype v o i d q u i c k s o r t i

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: p e l i s t [ ] , i n t l e f t , i n t r i g h t ) / / P o s t c o n d i t i o n: l i s t e l e m e n t s b e t w e e n i n d e x l e f t a n d // index right have been sorted into increasing order { if( left < right ) { int pivotPosition = p artition( list, left, right ); Q u i c k s o r t( l i s t , l e f t , p i v o t P o s i t i o n - 1 ) ; Q u i c k s o r t( l i s t , p i v o t P o s i t i o n + 1 , r i g h t ) ; } } So when can we say that f(n) is O(n log n)? CPSC 260 Quicksort Page 5 CPSC 260 Quicksort Page 6 Analysis of Quicksort Algorithm In the ideal case, the array of length N is partitioned into two equal pieces of length N/2. Each of these pieces is then partitioned into two pieces of length N/4 etc. N N/2 N/4 1 N/4 N/4 1 Similarly it can be argued that on each level, the partitioning operation requires O(N) work. 1 CPSC 260 Quicksort 1 Page 7 It can also be shown that in the average case the time complexity of the Quicksort algorithm is O( N log N ). Unfortunately, the Quicksort algorithm presented here can degrade in the case when the partitioning always results in one partition having size 0. This occurs, for example, when the pivot element is chosen to be the first element in the array and the array is already sorted. To partition an array of length N requires us to compare each element in the array with the pivot element for a total of N – 1 comparisons – an O(N) operation. We then partition two arrays of length N/2. Each array of length N/2 requires ( N/2 – 1 ) comparisons for a total of 2 * ( N/2 – 1 ) comparisons – again an O(N) operation. N/2 N/4 Each level in the diagram above represents a recursive step in the Quicksort algorithm. Notice that on each call to Quicksort, all the “work” is done by the partitioning function. In this ideal case where at each step the array is partitioned into two pieces of equal length, the total number of levels in the tree is O( log N ). Hence, in this case the time complexity of the Quicksort algorithm...
View Full Document

This document was uploaded on 02/25/2014 for the course CPSC 260 at The University of British Columbia.

Ask a homework question - tutors are online