See Lafore, page 316.
partition()
. What is your opinion of your colleague’s idea?
Using the first three values would be marginally easier than computing the mid-point index value, but it almost completely ignores the point behind using the median-of-three pivot. If the array segment is amost sorted, using three the median of three consecutive values would still leave the pivot towards one end of the segment, driving partition, and so quicksort, into worst-case behavior.
Dividing an array segment into thirds rather than halves effects mergesort’s recursive depth: rather than recursing log2 n levels for an array with n elements, it will resurce log3 n levels. Each level still does the same amount of O(n) work. A three-splitting mergesort does O(n log n) work.
The O(n2) sorts considered were
Quicksort: In the worst case, quicksort partitions an n-element array into 1-element and n-1-element partitions. This sequence of partitionings occurs O(n) times. Each partitioning uses, worst case, O(n) comparisons and O(n) assignments, for a total O(n2) comparisons and assignments, worst case.
It doesn't matter how partitioning finds the pivot value: left-most, median-of-three, random choice, and so on. Each of these techniques only makes it less likely that quicksort will encounter the worst case; they don't eliminate the possibility of encountering the worst case.
This page last modified on 30 November 2009.