More on swapping two variables without using the third one

No matter what you do, sometimes you just need to swap some values – I guess you did it thousand times. And yes, I know – this problem is trivial. In Python it’s completely trivial. You just swap two variables in the most “natural” way:

1
a, b = b, a

instead of doing it this way:

1
2
3
tmp = a
a = b
b = tmp

Beautiful! This is why we love Python, isn’t it?

That’s the moment where I should end this post, if it was about doing it in a “pythonic” way only. But it’s not – it’s about the ideas, not the solutions in any specific language. So…

I was just curious if there are any other “tricks” I could use to do the same thing – to swap two variables without using temporary one. So, my first, misty idea was about adding/subtracting or multiplying/dividing these values. The second solution fails for zeros, so I picked the first one. It wasn’t very obvious, but when I got the idea it was trivial to write the solution:

1
2
3
a = a + b
b = a - b
a = a - b

Looks good, but it has a small drawback – in most of the languages we can exceed the variable “capacity” (make an overflow) during the computation. Python is safe because of its “ability” to handle big numbers, but try it in C++ and check the values stored in variables in each step. It’s going to work, but I wanted to find something better. And I found this XOR solution:

1
2
3
a ^= b
b ^= a
a ^= b

Nice one! It’s in some way similar to the previous solution and it’s not very difficult to understand – you can find very nice explanation on Wikipedia in
XOR Swap Algorithm article. You can even find a short note about the previous solution there.

The last, small, “visual” improvement we can do is:

1
a ^= b ^= a ^= b

Looks quite good!

So, as you can see, even such simple thing can be done in many different ways. Am I going to use any of the methods I described instead of the pythonic one? Of course not. But I liked this little investigation.

Some day I’ll find out how the XOR solution works on “processor level” to compare its performance to the temporary variable solution, but – for now – it’s enough!

Comments are closed.