问题
Why we say the bestcase for quicksort is that "each time we perform a partition we divide the list into two nearly equal pieces"? And how to prove this is exactly the so called "best case"?
回答1:
Take array of length 2^N
(for simplicity).
Compare number of operations for the case of perfect partitions at every stage (N
into N/2+N/2
) and for the case of division of segment length N
into 1
and N-1
回答2:
I created a program rather than trying to do an analysis. I compared the case of 1/2, 1/2 (50% 50%) split versus 1/4, 3/4 (25% 75%) split, which appears to approach taking 22% more operations as n becomes large. The code is set for the 1/4,3/4 split: for 1/2,1/2 split, change the line from left = (n+3)/4 to left = (n+1)/2. The point of rounding left up is to make sure left >= 1, to avoid infinite recursion.
#include <stdio.h>
typedef unsigned long long uint64_t;
static uint64_t sum;
void qsa(uint64_t n)
{
uint64_t left, right;
if(n < 2)
return;
sum += n;
left = (n+3)/4; /* or left = (n+1)/2 */
right = n - left;
qsa(left);
qsa(right);
}
int main()
{
qsa(1024*1024);
printf("%llu\n", sum);
return(0);
}
results
n = 1024*1024
20971520 1/2 1/2 n log2(n)
25331387 1/4 3/4 ~1.208 n log2(n)
n = 16*1024*1024
402653184 1/2 1/2 n log2(n)
488049677 1/4 3/4 ~1.212 n log2(n)
n = 1024*1024*1024
32212254720 1/2 1/2 n log2(n)
39180282211 1/4 3/4 ~1.216 n log2(n)
n = 16*1024*1024*1024
584115552256 1/2 1/2 n log2(n)
711608157825 1/4 3/4 ~1.218 n log2(n)
来源:https://stackoverflow.com/questions/54759382/how-to-prove-the-evenly-partition-is-the-best-case-for-quick-sort-algorithm