Saturday, January 4, 2014

Swap two variables in five different ways

Perhaps the oldest technique most of programmers use, whether beginners or professional coders, to swap 2 variables a and b, is to declare a new temporary variable c, copy a to c then assign b to a and finally assign c to b.

book swap

But I am giving you 5 simple way to swap two variables:


a. /* swapping using three variables*/ (Takes extra memory space)

int a=5, b=10, c;
c=a;
a=b;
b=c;

b. /* using arithmetic operators */

a=a+b;
b=a-b;
a=a-b;

c. /* using bit-wise operators */

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

d. /* one line statement using bit-wise operators */ (most efficient)

a^=b^=a^=b;
The order of evaluation is from right to left. This is same as in approach (c), but the three statements are compounded into one statement.

e. /* one line statement using arithmetic & assignment operators */

a=(a+b) - (b=a);
In the above example, parenthesis operator enjoys the highest priority & the order of evaluation is from left to right. Hence (a+b) is evaluated first and replaced with 15. Then (b=a) is evaluated and the value of a is assigned to b, which is 5. Finally a is replaced with 15-5, i.e. 10. Now the two numbers are swapped.

2 comments: