In order to continue enjoying our site, we ask that you confirm your identity as a human. Thank you very much for your cooperation.
On some rare machines where branching is expensive, the below obvious approach to find minimum can be slow as it uses branching.
Below are the methods to get minimum(or maximum) without using branching. Typically, the obvious approach is best, though. Method 1(Use XOR and comparison operator) It works because if x < y, then -(x < y) will be -1 which is all ones(11111….), so r = y ^ ((x ^ y) & (111111…)) = y ^ x ^ y = x. And if x>y, then-(x<y) will be -(0) i.e -(zero) which is zero, so r = y^((x^y) & 0) = y^0 = y. On some machines, evaluating (x < y) as 0 or 1 requires a branch instruction, so there may be no advantage.
Output: Minimum of 15 and 6 is 6 Maximum of 15 and 6 is 15Time Complexity: O(1) Auxiliary Space: O(1) Method 2(Use subtraction and shift) , then we can use the following, which are faster because (x – y) only needs to be evaluated once. This method shifts the subtraction of x and y by 31 (if size of integer is 32). If (x-y) is smaller than 0, then (x -y)>>31 will be 1. If (x-y) is greater than or equal to 0, then (x -y)>>31 will be 0. So if x >= y, we get minimum as y + (x-y)&0 which is y. If x < y, we get minimum as y + (x-y)&1 which is x. Similarly, to find the maximum use x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)))
Time Complexity: O(1) Auxiliary Space: O(1) Note that the 1989 ANSI C specification doesn’t specify the result of signed right-shift, so above method is not portable. If exceptions are thrown on overflows, then the values of x and y should be unsigned or cast to unsigned for the subtractions to avoid unnecessarily throwing an exception, however the right-shift needs a signed operand to produce all one bits when negative, so cast to signed there. Method 3 (Use absolute value) A generalized formula to find the max/min number with absolute value is : (x + y + ABS(x-y) )/2Find the min number is: (x + y - ABS(x-y) )/2So, if we can use the bitwise operation to find the absolute value, we can find the max/min number without using if conditions. The way to find the absolute way with bitwise operation can be found here: Step1) Set the mask as right shift of integer by 31 (assuming integers are stored as two’s-complement 32-bit values and that the right-shift operator does sign extension). mask = n>>31Step2) XOR the mask with number mask ^ nStep3) Subtract mask from result of step 2 and return the result. (mask^n) - maskTherefore, we can conclude the solution as follows:
Time Complexity: O(1) Auxiliary Space: O(1) Article Tags : Practice Tags : |