The median of three numbers is the one that has the middle value of all three. In other words, if the three numbers are sorted, the one in the middle is the median.
There are several ways of comparing operations among variable a, b and c to determine which one is the median.
One brute force way is to directly represent verify the following formula:
a <= b <= c
if (a <= b and b <= c) or (c <= b and b <= a):
median = b
if (b <= a and a <= c) or (c <= a and a <= b):
median = a
if (a <= c and c <= b) or (b <= c and c <= a):
median = c
There are at most 6 comparisons in total. We can do better with some more mathematical deductions.
Below is the proof that we can reduce the amount of comparison to 3 (or less):
