Find maximum, minimum of three numbers without using conditional statements

Given three integers, find maximum and minimum number between them without using conditional statements or ternary operator.


 

Approach 1: (Using short-circuiting in Boolean expressions)

The idea is to take advantage of short-circuiting in Boolean expressions. We know that in Boolean AND operation such as x && y, y is evaluated only if x is true. If x is false, then y is not evaluated, because the whole expression would be false which can be deduced without even evaluating y. This is called short-circuiting in Boolean expressions.

The idea is to apply this principle to the below code. Initially max is a. Now if (max < b) is true, then that means, b is greater than a so the second sub-expression (max = b) is evaluated and max is set to b. If however (max < b) is false, then second sub-expression will not be evaluated and max will remain a (which is greater than b). In a similar fashion, the second expression is evaluated.

We can implement minimum function as well in similar fashion.
 

 

Download   Run Code

 

Approach 2: (Using array index)

 

Download   Run Code

 

Approach 3: (Approach 2 Simplified)

We can simplify approach 2 by breaking the problem into finding maximum/minimum of two numbers.

 

Download   Run Code

We can implement minimum function as well in similar fashion.

 

Download   Run Code

 

Approach 4: (Using repeated subtraction)

 

Download   Run Code

 

References: http://stackoverflow.com/questions/7074010/find-maximum-of-three-number-in-c-without-using-conditional-statement-and-ternar

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding :)
 



Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
bradley
Guest

#include <iostream>
using std::cout;
using std::endl;

template<typename T0, typename T1>
auto max(T0 a, T1 b) {
return 1./2. * (a + b + abs(a - b));
}

template<typename T0, typename T1, typename T2>
auto max3(T0 a, T1 b, T2 c) {
return max(a, max(b, c));
}

int main() {
cout << "max(2.001, 2): " << max(2.001, 2) << endl;
cout << "max(2, 1): " << max(2, 1) << endl;
cout << "max(2, 2): " << max(2, 2) << endl;
cout << "max(0, 0): " << max(0, 0) << endl;
cout << "max(-1, -10): " << max(-1, -10) << endl;
cout << "max(-1, 0): " << max(-1, 0) << endl;
cout << "max(1, -10): " << max(1, -10) << endl;

cout << "max3(2.001, 2, 4): " << max3(2.001, 2, 4) << endl;
cout << "max3(2, 1, 0): " << max3(2, 1, 0) << endl;
cout << "max3(2, 2, -1): " << max3(2, 2, -1) << endl;
cout << "max3(0, 0, 0): " << max3(0, 0, 0) << endl;
cout << "max3(-1, -10, -3): " << max3(-1, -10, -3) << endl;
cout << "max3(-1, 0, 10): " << max3(-1, 0, 10) << endl;
cout << "max3(1, -10, -2): " << max3(1, -10, -2) << endl;
}