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 » 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 :)
I'm Italian but we can speak C++ :)

Manolo
Ultimate wxWidgets Guru
Ultimate wxWidgets Guru
Posts: 660
Joined: Mon Apr 30, 2012 11:07 pm

Re: Swap without third variable (3 methods)

Post by Manolo » 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?

User avatar
doublemax
Moderator
Moderator
Posts: 13183
Joined: Fri Apr 21, 2006 8:03 pm
Location: $FCE2

Re: Swap without third variable (3 methods)

Post by doublemax » Fri Nov 28, 2014 5:49 pm

Use the source, Luke!

Post Reply