Consider three values x, y, z
.
What would be the formula to get the mid value (not the mean value but the value which is neither the min
nor the max
)?
const double min = std::min(x, std::min(y, z));
const double mid = /* what formula here ? */
const double max = std::max(x, std::max(y, z));
if you are able to find maximum and minimum values, you can find the middle value like this: int a = 1, b = 2, c = 3; int minVal = min(a, b); int maxVal = max(maxVal, c); int midVal = a + b + c - maxVal - minVal; midVal should contain the middle value of those 3 numbers.
Find the size n of the array. Usually done by sizeof array / sizeof array[0] . Index array[n/2] to find midpoint.
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)
...
max(min(x,y),z)
. Through this we are able to determine the relation between min(x,y) and z.max(min(x,y),z)
returns that.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 becomes max(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With