15 - Quicksort

Hence in this case the time complexity of the

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: is O( N log N ). CPSC 260 Quicksort Page 8 In this case the partitioning of the first level requires N – 1 comparisons as before. However, on the next level, N – 2 comparisons are required, then N – 3 etc. down to 0 on the last level when there is only one element. Total # of comparisons: 0+1+2+…+N–1 =N(N–1)/2 N Hence, in this worst case, Quicksort degrades to an O(N2) algorithm. N-1 N-2 1 CPSC 260 Quicksort Page 9 Space complexity Recall that whenever a function is called, an activation record is generated. This activation record stores parameter values and the value of local variables in the function (among other things). The amount of space required by our Quicksort algorithm therefore depends on the maximum number of activation records generated by calls to the Quicksort function. In the ideal case, we can see that there will be !log 2 N " + 1 levels (see p. 6) and hence the Quicksort algorithm requires O( log N ) space in this case. In the worst case, there are N levels and hence the space requirement degrades to O(N). This can create a problem given that the run-time stack has a limited capacity – it is possible that for large N all the space in the stack segment will be consumed leading to a stack overflow. CPSC 260 Quicksort Page 11 CPSC 260 Quicksort Page 10 Improving the Quicksort Algorithm Choosing a better pivot element We have seen that when the pivot element is chosen to be the first element in the array, the performance of Quicksort degrades in the case when the array is already sorted. We can guarantee a best-case performance if the pivot element is the median element (the one in the middle when the data is sorted) because then half the elements will be smaller than the pivot and half larger so the partitions will have equal size. Unfortunately, determining the median element requires us to sort the data first so this is obviously not reasonable (or at least have a more complicated algorithm). Instead, we can attempt to estimate the median element by...
View Full Document

Ask a homework question - tutors are online