Given is an array of three numeric values and I'd like to know the middle value of the three.
The question is, what is the fastest way of finding the middle of the three?
My approach is this kind of pattern - as there are three numbers there are six permutations:
if (array[randomIndexA] >= array[randomIndexB] && array[randomIndexB] >= array[randomIndexC])
It would be really nice, if someone could help me out finding a more elegant and faster way of doing this.
It is also useful to know what number is mid-way between the least value and the greatest value of the data set. This number is called the midrange. To find the midrange, add together the least and greatest values and divide by two, or in other words, find the mean of the least and greatest values.
To find the median of any set of numbers, put them in order from smallest to greatest. If a number occurs more than once, list it more than once. The number in the middle is the median.
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.
There's an answer here using min/max and no branches (https://stackoverflow.com/a/14676309/2233603). Actually 4 min/max operations are enough to find the median, there's no need for xor's:
median = max(min(a,b), min(max(a,b),c));
Though, it won't give you the median value's index...
Breakdown of all cases:
a b c 1 2 3 max(min(1,2), min(max(1,2),3)) = max(1, min(2,3)) = max(1, 2) = 2 1 3 2 max(min(1,3), min(max(1,3),2)) = max(1, min(3,2)) = max(1, 2) = 2 2 1 3 max(min(2,1), min(max(2,1),3)) = max(1, min(2,3)) = max(1, 2) = 2 2 3 1 max(min(2,3), min(max(2,3),1)) = max(2, min(3,1)) = max(2, 1) = 2 3 1 2 max(min(3,1), min(max(3,1),2)) = max(1, min(3,2)) = max(1, 2) = 2 3 2 1 max(min(3,2), min(max(3,2),1)) = max(2, min(3,1)) = max(2, 1) = 2
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