Swap Without a Temp Variable

code
swapping
efficient

(oaktree) #1

Hey everyone! I just thought I would share this little technique, because it was unknown to me after a year of programming experience!

int a = 5, b = 6;

// swapping now:

a = a + b; 
// a = 11

b = a - b; 
// b = a + b - b
// b = a
// b = 5

a = a - b; 
// a = a + b - (a + b - b)
// a = b
// a = 6

In the code’s comments, I used substitution to prove that this method works.

You may have already known about this, but since it took me a year to find out, I thought I would expedite the process for my pals at 0x00sec!

Swap on,
oaktree


#2

Very nice! How Python spoils us:

a, b = b, a 

:joy:


(oaktree) #3

The same goes for Ruby.


(oaktree) #4

This topic was automatically closed after 30 days. New replies are no longer allowed.