Jul 052012

Given two unsigned integers, find the larger (or smaller) of the two without using branching (if-else or conditional operator).

**Solution:**

If given numbers are x and y, then the obvious answer is

max = (x>y) ? x : y;

But it is using branching (conditional operator). Without using branching, you may choose the below method to find the largest.

x ^ ((x ^ y) & -(x < y));

This method relies on the fact that XOR with 0 will result in the number itself, i.e

x ^ 0 == x

and XOR of a number with itself will be zero. i.e

x ^ x == 0