Question

Quicksort and Median use the same method (Divide and concuer), why is it then that they have different asymptotic behavior?

Is it that quicksort may not use the proper pivot?

Was it helpful?

Solution 2

If you use Hoare's original select algorithm, you can get the same sort of poor worst case performance that you can from Quicksort.

If you use the median of medians, then you limit the worst case, at the expense of being slower in most typical cases.

You could use the median of medians to find a pivot for Quicksort, which would have roughly the same effect--limit the worst case, at the expense of being slower in most cases.

Of course, for the sort (in general) each partition operation is O(N), and you expect to do about log(N) partition operations, so you get approximately O(N log N) overall complexity.

With median finding, you also expect to do approximately O(log N) steps, but you only consider the partition from the previous step that can include the median (or quartile, etc. that you care about). You expect the sizes of those partitions to divide by (approximately) two at every step, rather than always having to partition the entire input, so you end up with approximately O(N) complexity instead of O(N log N) overall.

[Note that throughout this, I'm sort of abusing big-O notation to represent expected complexity whereas big-O is really supposed to represent the upper-bound (i.e., worst-case) complexity.]

OTHER TIPS

When you use method partition in Quicksort (see method in the link) to find the median, the method return index of element which have correct position, based on this position, you only need to check for selected parts which contains the median.

For example array length is 5, so median is 3. The partition method return 2, so you only need to check the upper part of the array from 2 to 5, not the whole array as Quicksort.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top