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 how it is better than the randomized quick sort.
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 how it is better than the randomized quick sort.
The median of three has you look at the first, middle and last elements of the array, and choose the median of those three elements as the pivot.
To get the "full effect" of the median of three, it's also important to sort those three items, not just use the median as the pivot -- this doesn't affect what's chosen as the pivot in the current iteration, but can/will affect what's used as the pivot in the next recursive call, which helps to limit the bad behavior for a few initial orderings (one that turns out to be particularly bad in many cases is an array that's sorted, except for having the smallest element at the high end of the array (or largest element at the low end). For example:
Compared to picking the pivot randomly:
That second point probably bears a bit more explanation. If you used the obvious (rand()
) random number generator, it's fairly easy (for many cases, anyway) for somebody to arrange the elements so it'll continually choose poor pivots. This can be a serious concern for something like a web server that may be sorting data that's been entered by a potential attacker, who could mount a DoS attack by getting your server to waste a lot of time sorting the data. In a case like this, you could use a truly random seed, or you could include your own PRNG instead of using rand() -- or you use use Median of three, which also has the other advantages mentioned.
On the other hand, if you use a sufficiently random generator (e.g., a hardware generator or encryption in counter mode) it's probably more difficult to force a bad case than it is for a median of three selection. At the same time, achieving that level of randomness typically has quite a bit of overhead of its own, so unless you really expect to be attacked in this case, it's probably not worthwhile (and if you do, it's probably worth at least considering an alternative that guarantees O(N log N) worst case, such as a merge sort or heap sort.
rand()
is typically a linear congruential generator. One method for such generators is described on Crypto.SE. In theory, rand() could be a cryptographically secure generator, but that's rare (to say the least).
Aug 19, 2013 at 7:12
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 bitwise XOR
operator. So you would read:
a
greater than exclusively one of the others? return a
b
smaller than exclusively one of the others? return b
return c
Note that by switching the comparison for b
the method also covers all cases where some inputs are equal. Also that way we repeat the same comparison a > b
is the same as b < a
, smart compilers can reuse and optimize that.
The 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 seem a bit hacky, under the hood it is compiling to the very efficient XOR
assembly operator.
int limit = 1000000; while (limit-- > 0) { }
volatile
to force the variable value to be unknown to the compiler, would that work?
Jan 31 at 23:48
printf()
, so the compiler is forced to produce a correct result. Interestingly, I don't notice any actual x86 XOR instructions in there. The compiler found another approach.
An implementation of Median of Three I've found works well in my quick sorts.
(Python)
# Get the median of three of the array, changing the array as you do.
# arr = Data Structure (List)
# left = Left most index into list to find MOT on.
# right = Right most index into list to find MOT on
def MedianOfThree(arr, left, right):
mid = (left + right)/2
if arr[right] < arr[left]:
Swap(arr, left, right)
if arr[mid] < arr[left]:
Swap(arr, mid, left)
if arr[right] < arr[mid]:
Swap(arr, right, mid)
return mid
# Generic Swap for manipulating list data.
def Swap(arr, left, right):
temp = arr[left]
arr[left] = arr[right]
arr[right] = temp
arr[left], arr[right] = arr[right], arr[left]
The common/vanilla quicksort selects as a pivot the rightmost element. This has the consequence that it exhibits pathological performance O(N²) for a number of cases. In particular the sorted and the reverse sorted collections. In both cases the rightmost element is the worst possible element to select as a pivot. The pivot is ideally thought to me in the middle of the partitioning. The partitioning is supposed to split the data with the pivot into two sections, a low and a high section. Low section being lower than the pivot, the high section being higher.
Median-of-three pivot selection:
The common pathologies O(N²) of sorted / reverse sorted inputs are mitigated by this. It is still easy to create pathological inputs to median-of-three. But it is a constructed and malicious use. Not a natural ordering.
Randomized pivot:
If random, this does not exhibit pathological O(N²) behavior. The random pivot is usually quite likely computationally intensive for a generic sort and as such undesirable. And if it's not random (i.e. srand(0); , rand(), predictable and vulnerable to the same O(N²) exploit as above.
Note that the random pivot does not benefit from selecting more than one element. Mainly because the effect of the median is already intrinsic, and a random value is more computationally intensive than the ordering of two elements.
Think simple... Python example....
def bigger(a,b): #Find the bigger of two numbers ... if a > b: return a else: return b def biggest(a,b,c): #Find the biggest of three numbers ... return bigger(a,bigger(b,c)) def median(a,b,c): #Just dance! x = biggest(a,b,c) if x == a: return bigger(b,c) if x == b: return bigger(a,c) else: return bigger(a,b)
This strategy consists of choosing three numbers deterministically or randomly and then use their median as pivot.
This would be better because it reduces the probability of finding "bad" pivots.
We can understand the strategy of median of three by an example, suppose we are given an array:
[8, 2, 4, 5, 7, 1]
So the leftmost element is 8
, and rightmost element is 1
. The middle element is 4
, since for any array of length 2k, we will choose the kth element.
And then we sort this three elements in either ascending order or descending order which gives us:
[1, 4, 8]
Thus, the median is 4
. And we use 4
as our pivot.
On the implementation side, we can have:
// javascript
function findMedianOfThree(array) {
var len = array.length;
var firstElement = array[0];
var lastElement = array[len-1];
var middleIndex = len%2 ? (len-1)/2 : (len/2)-1;
var middleElement = array[middleIndex];
var sortedArray = [firstElement, lastElement, middleElement].sort(function(a, b) {
return a < b; //descending order in this case
});
return sortedArray[1];
}
Another way to implement it is inspired by @kwrl, and I'd like to explain it a little bit clearer:
// javascript
function findMedian(first, second, third) {
if ((second - first) * (third - first) < 0) {
return first;
}else if ((first - second) * (third - second) < 0) {
return second;
}else if ((first - third)*(second - third) < 0) {
return third;
}
}
function findMedianOfThree(array) {
var len = array.length;
var firstElement = array[0];
var lastElement = array[len-1];
var middleIndex = len%2 ? (len-1)/2 : (len/2)-1;
var middleElement = array[middleIndex];
var medianValue = findMedian(firstElement, lastElement, middleElement);
return medianValue;
}
Consider the function findMedian
, first element will be return only when second Element > first Element > third Element
and third Element > first Element > second Element
, and in both cases: (second - first) * (third - first) < 0
, the same reasoning apply to the remaining two cases.
The upside of using the second implementation is that it could have a better run time.
I think rearranging the values in the array is not necessary for just three values. Just compare all of them by subtracting; then you can decide which one is the median value:
// javascript:
var median_of_3 = function(a, b, c) {
return ((a-b)*(b-c) > -1 ? b : ((a-b)*(a-c) < 1 ? a : c));
}