One Definition Rule (ODR) in C++
July 4, 2012
Minimum Stack: Stack returning min element in O(1) time
July 5, 2012

Find larger of 2 elements without branching

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

Leave a Reply

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