#include <iostream>
using std::cout;
using std::endl;
// Check whether x is the median of (x, y, z)
bool isMedian(int x, int y, int z) {
// x is median if it lies between y and z
// (either y <= x <= z OR z <= x <= y)
if ((x >= y && x <= z) || (x <= y && x >= z)) {
return true;
} else {
return false;
}
}
// Return the median of three numbers using the helper function
int median_of_three_numbers(int a, int b, int c) {
if (isMedian(a, b, c)) {
return a;
}
if (isMedian(b, c, a)) {
return b;
}
// If neither a nor b is the median, then c must be
return c;
}
int main() {
cout << "The median of [1, 1, 1] is "
<< median_of_three_numbers(1, 1, 1) << endl;
cout << "The median of [10, 3, 7] is "
<< median_of_three_numbers(10, 3, 7) << endl;
cout << "The median of [10, -10, -10] is "
<< median_of_three_numbers(10, -10, -10) << endl;
cout << "The median of [3, 3, 5] is "
<< median_of_three_numbers(3, 3, 5) << endl;
return 0;
}
/*
run:
The median of [1, 1, 1] is 1
The median of [10, 3, 7] is 7
The median of [10, -10, -10] is -10
The median of [3, 3, 5] is 3
*/