Below are the methods to get minimum(or maximum) without using branching.

  • Using XOR and comparison operator
    Minimum of x and y will be

    Min(x,y) = y ^ ((x ^ y) & -(x < y))

    It works because if x < y, then -(x < y) will be all ones, so r = y ^ (x ^ y) & ~0 = y ^ x ^ y = x. Otherwise, if x >= y, then -(x < y) will be all zeros, so r = y ^ ((x ^ y) & 0) = y.

    Similarly the maximum of two integers can be found from the following:

    Max(x,y) = x ^ ((x ^ y) & -(x < y))

    Hence the code for caculating minimum and maximum is given by

    // Function to find minimum of x and y
    int min(int x, int y)
    {
      return y ^ ((x ^ y) & -(x < y));
    }
      
    // Function to find maximum of x and y
    int max(int x, int y)
    {
      return x ^ ((x ^ y) & -(x < y));
    }
  •  Using subtraction and shift
    Here is a another solution which uses the fact that a number is stored in its 2’s complement form where the msb (most significant bit) is 0, if the number is positive, otherwise its 1.

    int getMax(int x, int y) {
      int c = x - y;  
      int k = (c >> 31) & 0x1;  
      int max = x - k * y;  
      return max;  
    }

    Here, c stores the difference of x and y. Right shifting c by 31 times gives the msb of c; bit wise AND with 1 results in 1 if x < y, and 0 if x > y.

  • Using middle value
    Consider a straight line with the two numbers as its end-points. Now the larger number, say y, is away from their midpoint M by half the distance between the two endpoints. If d be the distance between x and y and M be the midpoint, then larger number is

    // Large number
    y = M + d /2
    
    // Since
    M = (x+y)/2
    d = | x - y |