Given five random elements, it’s possible to find the median using just six comparisons. But I have an extra requirement in that the following condition is also satisfied:
a < c && b < c && c < d && c < e
It is NOT required for a < b or d < e.
I’ve been able to satisfy this condition using seven comparisons, but not six. This is my code, which should be self explanatory:
void medianSort(int[] arr)
{
assert(arr.length == 5);
void sortPair(ref int a, ref int b)
{
if(a > b) swap(a, b);
}
sortPair(arr[0], arr[1]);
sortPair(arr[3], arr[4]);
sortPair(arr[0], arr[3]);
sortPair(arr[1], arr[4]);
sortPair(arr[2], arr[3]);
sortPair(arr[1], arr[2]);
sortPair(arr[2], arr[3]);
}
I have a quick sort that I wish to enhance by using a median of five to choose the pivot. By satisfying that condition, five elements are already sorted.
Is it possible to accomplish this in six comparisons, or is seven the best I can do?
I grinded away at the problem for two hours, but I found a solution. The important thing is to keep track of the comparisons made, which I’ve done in great detail with the comments. The function is written in D.
Python: http://pastebin.com/0kxjxFQX