Search This Blog

Google Analytics

Thursday, June 21, 2007

Efficient Swap

Usually, when we wish to do swapping of values, we usually use a temporary variable like below (C# syntax but can easily be converted to other programming languages). However, it is not that efficient especially if you have lots of swapping to do.
// May use other datatypes like int
byte a, b;
byte temp;

a = 1;
b = 2;

// Do swapping now
temp = a;
a = b;
b = temp;

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

A more efficient swapping of variable values (C# syntax but can easily be converted to other programming languages) is illustrated below.

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.

Popular Posts