Find maximum of two integers without if-else and comparison

© Parineeth M R

Question 37. Find the maximum of 2 integers without using if-else or any other comparison operator


We can find the maximum of 2 integers without making use of if else or any comparison operator using the function below

C/C++


/*Returns the maximum of x and y without using if-else and comparison*/
int find_max(int x, int y) {
	int difference = x - y;
	int sign_bit = 	(difference >> 31) & 0x1;
	/*
	Sign bit can be 0 or 1
	If sign bit is 0, max = x - (0 * difference) = x
	If sign bit is 1, max = x - (1 * (x-y)) = x - x + y = y 
	*/
	int max = x  - (sign_bit * difference);
	return max;
}



Java


/*Returns the maximum of x and y without using if-else and comparison*/
public static int findMax(int x, int y) {
	int difference = x - y;
	int signBit = 	(difference >> 31) & 0x1;
	/*
	Sign bit can be 0 or 1
	If sign bit is 0, max = x - (0 * difference) = x
	If sign bit is 1, max = x - (1 * (x-y)) = x - x + y = y 
	*/
	int max = x  - (signBit * difference);
	return max;
}



Python


#Returns the maximum of x and y without using if-else and comparison
# Maximum value of x and y should not exceed 31 bits
def find_max(x, y) :
	difference = x - y
	sign_bit = (difference >> 31) & 0x1
	
	#Sign bit can be 0 or 1
	#If sign bit is 0, max = x - (0 * difference) = x
	#If sign bit is 1, max = x - (1 * (x-y)) = x - x + y = y 
	max_value = x  - (sign_bit * difference)
	return max_value



First we compute the difference between x and y. Next we find the sign bit of the difference. In the 2’s complement notation, the most significant bit indicates the sign of the number. If the sign bit is 0, then the number is positive and if the bit is 1, then the number is negative.

If x >= y, then the difference x – y is positive and so the sign bit of the difference is 0.

If x < y, then the difference x – y is negative and sign bit of the difference is 1.

Then we compute max = x – (sign_bit * difference).

If x >= y, then sign_bit = 0 and max = x – (0 * difference) = x. So we return x as the maximum value

If x < y, then sign_bit = 1 and max = x - (1 * difference) = x - difference = x - (x - y) = y. So we return y as the maximum value