Swap without third variable (3 methods)

If you have a cool piece of software to share, but you are not hosting it officially yet, please dump it in here. If you have code snippets that are useful, please donate!
Post Reply
wxProgrammer
Experienced Solver
Experienced Solver
Posts: 96
Joined: Thu Apr 17, 2014 10:10 am

Swap without third variable (3 methods)

Post by wxProgrammer »

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 :)
I'm Italian but we can speak C++ :)
Manolo
Can't get richer than this
Can't get richer than this
Posts: 827
Joined: Mon Apr 30, 2012 11:07 pm

Re: Swap without third variable (3 methods)

Post by Manolo »

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?
User avatar
doublemax
Moderator
Moderator
Posts: 19115
Joined: Fri Apr 21, 2006 8:03 pm
Location: $FCE2

Re: Swap without third variable (3 methods)

Post by doublemax »

Use the source, Luke!
Post Reply