Sunday, March 07, 2010

Efficient swapping of values using XOR

A more efficient method in swapping values of 2 variables can be done using XOR operation instead of creating a third variable for temporary storage.

The below C# code snippet illustrates just that.

byte a, b; // May use other datatypes like int

a = 1;
b = 2;

a ^= b;
b ^= a;
a ^= b;

// Now a and b are swapped
////

No comments:

Post a Comment

Do provide your constructive comment. I appreciate that.