Find the Maximum of Two Numbers Without Using if-else

Find the maximum and minimum of two integers without branching i.e. if condition.

Solution:
Minimum of two numbers can be found from the following:

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. On some machines, evaluating (x < y) as 0 or 1 requires a branch instruction, so there may be no advantage.

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

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

#include<stdio.h>
 
/*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));
}

0 Thoughts on “Find the Maximum of Two Numbers Without Using if-else

  1. Is this correct way to do above question??

    #include<stdio.h>
    int main(void)
    { int a,b;
    a=7;
    b=9;

    int c;

    c=a/b;

    switch(c)
    {
    case 0:
    printf("Bigger is %d",b);
    break;
    default:
    printf("Bigger is %d",a);
    break;

    }
    return 0;
    }

  2. John Justin on July 14, 2016 at 11:57 am said:

    My Solution:

    min=(a+b)/2 – abs(a-b)/2

    max=(a+b)/2 + abs(a-b)/2

  3. int main()
    {
    int a=7,b=9;
    printf(“%d”,a>b?a:b);
    }

  4. Thank you so much madhu!!!!!

  5. Ankush Batra on November 15, 2018 at 11:29 pm said:

    int find_max(int n1, int n2)
    {
    int r = n1-n2;
    r = (r>>31)&1;

    if(r=0)
    return n1;
    else
    return n2;
    }

Leave a Reply to Sparsh Chokra Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation