The answer from this link shared in the comments:
const double mid = std::max(std::min(x,y),std::min(std::max(x,y),z));
Edit - As pointed out by Alan, I missed out on a case. I have given now a more intuitive proof.
Direct Proof: Without Loss of Generality with respect to x and y.
Starting with the innermost expression, min(max(x,y),z)
...
- If it returns z, we have found the relations: max(x,y) > z. Then the expression evaluates to
max(min(x,y),z)
. Through this we are able to determine the relation between min(x,y) and z.
If min(x,y) > z, then z is smaller than x and y both (as the relation becomes: max(x,y) > min(x,y) > z). Therefore the min(x,y) is indeed the median andmax(min(x,y),z)
returns that.
If min(x,y) < z, then z is indeed the median (as min(x,y) < z < max(x,y)). - If it returns x, then we have x < z and y < z. The expressions evaluates to:
max(min(x,y),x)
. Since max(x,y) evaluated to x, min(x,y) evaluates to y. Getting the relation z > x > y. We return the max of x and y (as the expression becomesmax(y,x)
) which is x and also the median. (Note that the proof for y is symmetrical)
Proof Ends
Old Proof - Note it is NOT complete (Direct):
Without loss of generality:
Assume x > y > z
Min of x and y is y. And min of (max of x and y) and z is z.
The max of y and z is y which is the median.
Assume x = y > z
Min of x and y say is x. And min of (max of x and y is x) and z is z.
Max of the above two is x, which is the median.
Assume x > y = z
Min of x and y is y. And min of (max of x and y is x) and z is z.
Max of the above two is y, which is the median.
Finally, assume x = y = z
Any of the three numbers will be the median., and the formula used will return some number.