Tuesday, May 08, 2012

swapping two variables without using the third one

Case 1 : Variable is a number
If X = 4, Y = 2 We need to swap the values of X and Y Traditional approach involves a temporary variable
int x=4; y=2;
int temp;
temp = y;
y = x;
x = temp;

Optimal approach

X = X + Y; (X = 4+2 =6)
Y = X - Y; (Y = 6-2 =4)
X = X - Y; (X = 4-2 =2)

Final result : X= 2, Y=4