12/04/2012

How to swap two integer values without a temp variable?

This question has been asked to me for many times by my algorithm teachers. I just wanted to write about it to help new algorithm students to find the answer to their homeworks :)

Let a and b be two integer variables. To swap the values of these variables, some arithmetic operations as follows must be applied.

a = a - b;
b = b + a;
a = b - a;

Lets continue with a numerical example where
a = 3 and b = 5


a = 3 - 5 = -2;
b = 5 + (-2) = 3;
a = 3 - (-2) = 5;


As a result of these operations, the values are swapped without using any additional temporary variable. Now you can write down the answer to your homework :)