What is the median of three strategy to select the pivot value in quick sort?
I am reading it on the web, but I couldn\'t figure it out what exactly it is? And also
Think faster... C example....
int medianThree(int a, int b, int c) {
if ((a > b) != (a > c))
return a;
else if ((b > a) != (b > c))
return b;
else
return c;
}
This uses XOR like operator. So you would read:
a greater than exclusively one of the others? return ab greater than exclusively one of the others? return breturn cThe median approach is faster because it would lead to more evenly partitioning in array, since the partitioning is based on the pivot value.
In the worst case scenario with a random pick or a fixed pick you would partition every array into an array containing just the pivot and another array with the rest, leading to an O(n²) complexity.
Using the median approach you make sure that won't happen, but instead you are introducing an overhead for calculating the median.
Benchmarks results show XOR is 32 times faster than Bigger even though I optimized Bigger a little:
You need to recall that XOR is actually a very basic operator of the CPU's Arithmetic Logic Unit (ALU), then although in C it may seen a bit hacky, under the hood it is compiling to the very efficient XOR assembly operator.