Reputation: 57
I'm working on the program just needed in the following to understand it better.
What is the average case running time for Quick sort and what may cause this average case performance? How can we modify quick sort program to mitigate this problem?
I know that it has average case O(n log(n)) and I know it occurs when the pivot median element. My question is how can I modify the program to mitigate this problem.
Upvotes: 2
Views: 7768
Reputation: 51152
The average case of quicksort is not when the pivot is the median element - that's the best case. Analyzing the average case is a bit tricker. We'll assume that the array is in a random order, so that each element is equally likely to be selected as the pivot. Alternatively, we can just select the pivot randomly so that the original array order doesn't matter; either way leads to the same conclusion.
If the numbers in the array are [1, 2, 3, 4, 5]
, for example, then each number has a 1/5 probability of being selected as the pivot.
So the recurrence is that T(5)
is 1/5 of T(4) + T(0)
, T(3) + T(1)
, T(2) + T(2)
, T(1) + T(3)
and T(0) + T(4)
, plus an O(n) term for the cost of partitioning. The general form of this recurrence relation is a sum over every possible pivot, divided by the number of possible pivots:
The solution to this recurrence relation happens to be that T(n) is in O(n log n).
The fact that the quicksort algorithm runs in O(n log n) time in the average case is not a problem; in fact, this is asymptotically optimal for any comparison-based sorting algorithm. No comparison-based sorting algorithm can have a better asymptotic running time in the average case.
Upvotes: 6