Page 1 of 1

### Swap without third variable (3 methods)

Posted: Fri Nov 28, 2014 10:43 am
Hi, I've founded this three methods with my friend (foundef by ourself, not on internet but I think that they already exist).

The first and second metods are for numeric variables: it consists to merge the variable and next extracts it:
First:
A = 5;
B = 3;
A = A+B; //5+3=8
B = A-B; //8-3 = 5
A = A-B; //8-5 = 3

Second:
A = 6;
B = 9;
A = A-B; //6-9=-3
B = A+B; //-3+9=6
A = B-A; //6-(-3) =9

The third method is my favourite: it consist to merge it with the exclusive sum/exclusive or (XOR bit to bit)
/*
This is the XOR table: it is true when only one is true (or when the two bits are different)
x | y | x^y (In C/C++, ^ is XOR bit to bit)
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0
*/
A=255; //11111111
B=134; //10000110
A=A^B; //01111001
/*
11111111 ^
10000110 =
01111001
*/
B = A^B; //11111111 (255)
/*
01111001 ^
10000110 =
11111111
*/
A = A^B; //10000110 (134)
/*
01111001 ^
11111111 =
10000110
*/

It's all ### Re: Swap without third variable (3 methods)

Posted: Fri Nov 28, 2014 5:41 pm
The three methods are similar (A^B = A-B). And all of they are only valid for small int values. If you use big values, then A+B or A-B may be out of range.
Anyhow, what's the (great) advantage from the usal temp-var method?

### Re: Swap without third variable (3 methods)

Posted: Fri Nov 28, 2014 5:49 pm