An Algorithm to Swap Two Variables Synchronously, Without Creating a Temporary Variable


Let's say you want to swap the values of two integer variables, a, and b. Simply setting a equal to b and then b equal to a does not work, since a and b would just end up both equaling the initial value of b.

1# doesn't work (both a and b end up equaling b): 2a = b 3b = a 4

So, typically, you'd create another variable — let's call it c — and set that variable to the value of a, and then do something like this:

1# the simplest solution, with a temporary variable: 2c = a 3a = b 4b = c 5

This is very simple, but the extra variable is not actually necessary.

Note that some programming languages, for example Python, provide the ability to swap two variables in a single line, like a, b = b, a. I will explain how to swap two variables without a temporary variable without utilizing this feature.

The Algorithm

By summing the two variables and adding a few subtraction operations, this same swapping operation can be done without a temporary variable, like this:

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

To see that this works, let's test it out with a = 100 and b = 5.

1a = a + b # a = 100 + 5 = 105 2b = a - b # b = 105 - 5 = 100 3a = a - b # a = 105 - 100 = 5 4

As we can see, after running these operations, a = 5 and b = 100, so the values were swapped, as expected.

This can also be similarly done with multiplication and division, like this:

1a = a * b 2b = a / b 3a = a / b 4

This version is generally less efficient because most (if not all) programming languages take longer to calculate products and quotients in comparison to sums and differences.


Overall, this is an interesting algorithm that can be used in programs where you are swapping two integer values. Since it only saves a very small amount of space by not creating the temporary variable, it is not particularly useful in smaller projects and programs. However, on a larger scale when working with millions of variables and values at a time, and you'd like to save as much space and storage as possible, this can be useful.

I hope you enjoyed this article and found this to be an interesting algorithm.

Thanks for scrolling.

— Gabriel Romualdo, March 23, 2021