It is well known that the performance of quicksort can be substantially improved by selecting the median of a sample of three elements as the pivot of each partitioning stage. This variant is easily generalized to samples of size s = 2k + 1. For large samples the partitions are better as the median of the sample makes a more accurate estimate of the median of the array to be sorted, but the amount of additional comparisons and exchanges to nd the median of the sample also increases. We show that the optimal sample size to minimize the average total cost of quicksort (which includes both comparisons and exchanges) is s = a p n + o( p n ). We also give a closed expression for the constant factor a, which depends on the median-nding algorithm and the costs of elementary comparisons and exchanges. The result above holds in most situations, unless the cost of an exchange exceeds by far the cost of a comparison. In that particular case, it is better to select not the median of the samples, but the (p + 1) th element. The value of p can be precisely determined as a function of the ratio between the cost of an exchange and the cost of a comparison. We also show how to apply the same ideas and techniques to the analysis of quickselect, a general-purpose selection algorithm closely related to quicksort, and get similar results to those for quicksort.
In practice, it is usually chosen as the median in a sample of three elements, while theory suggests to choose it as the median of Θ( √ n) elements to minimize comparisons REF .
Optimal Sampling Strategies in Quicksort and Quickselect
PROC. OF THE 25TH INTERNATIONAL COLLOQUIUM (ICALP-98), VOLUME 1443 OF LNCS
Mathematics Computer Science