Saturday, May 05, 2007

Swapping Two Integer Variables Without Using a Temp Variable

The first time I heard this question, I thought it was a joke of some kind. I never thought such was possible.

Turned out to be possible and even faster than the normal technique, here you go:

Let X be an integer variable.
Let Y be another integer variable.
X = X xor Y
Y = X xor Y
X = X xor Y

Wont buy it? Then try it out for yourself.

One more technique, you can use the - (minus) operator instead, but be careful not to step over the integer max and min limits. Here you go:

(eg. X = 12, Y = 7)
X = X - Y ( X is now 5)
Y = X + Y ( Y is now 12)
X = Y - X ( X is now 7)
(result: X = 7, Y = 12, Voila! Swapped)

Hmmmm. Coming to think of a practical use. The only way such would be useful is to swap two large memory binary buffers.

This swapping enhancement breaks the common myth of 'its either memory or speed, but not both'. The swapping algorithm you just saw proves better in both memory consumption and performance gain.

3 comments:

Anonymous said...

did u come to this on ur own? willa u read about it? this is waaaaaay toooo coool!

ps. i decided im going back to programming ;)

Basil 3ibs said...

I'm sure I heard it somewhere. (Although, didnt read anything lately about it). Search google for any references, you should find something. The XOR I believe is popular. But I dont think you'll find the minus operator swapping technique ;)

Shaneena said...

Great :)