Difference between POP & IMAP
June 12, 2012
Rotating an array around a pivot
June 12, 2012

Compute Max and Min without branching

Given 2 unsigned integers, write expressions to find the maximum and minimum of these 2 integers without using either if-else or conditional operator.

Solution:

If the integers are a and b, as given below then the max & min can be computed like below:

   unsigned int a;
   unsigned int b;
   // Computing minimum
   int min = b ^ ( (a^b) & -(a<b) );
   // Computing maximum
   int max = a ^ ( (a^b) & -(a<b) );   

Leave a Reply

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