Compute the minimum or maximum of two integers without branching | C ++ program for the above approach ; absbit32 function ; max function ; min function ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int absbit32 ( int x , int y ) { int sub = x - y ; int mask = ( sub >> 31 ) ; return ( sub ^ mask ) - mask ; } int max ( int x , int y ) { int abs = absbit32 ( x , y ) ; return ( x + y + abs ) / 2 ; } int min ( int x , int y ) { int abs = absbit32 ( x , y ) ; return ( x + y - abs ) / 2 ; } int main ( ) { cout << max ( 2 , 3 ) << endl ; cout << max ( 2 , -3 ) << endl ; cout << max ( -2 , -3 ) << endl ; cout << min ( 2 , 3 ) << endl ; cout << min ( 2 , -3 ) << endl ; cout << min ( -2 , -3 ) << endl ; return 0 ; }