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

Gabe Romualdo @gaberomualdo

About: See many of my blog posts here on DEV.

Joined:
Aug 11, 2018

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

Publish Date: Mar 24 '21
29 11

Introduction

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.

# doesn't work (both a and b end up equaling b):
a = b
b = a
Enter fullscreen mode Exit fullscreen mode

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:

# the simplest solution, with a temporary variable:
c = a
a = b
b = c
Enter fullscreen mode Exit fullscreen mode

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:

a = a + b
b = a - b
a = a - b
Enter fullscreen mode Exit fullscreen mode

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

a = a + b # a = 100 + 5 = 105
b = a - b # b = 105 - 5 = 100
a = a - b # a = 105 - 100 = 5
Enter fullscreen mode Exit fullscreen mode

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:

a = a * b
b = a / b
a = a / b
Enter fullscreen mode Exit fullscreen mode

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.

Conclusion

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

Comments 11 total

  • Ben Sinclair
    Ben SinclairMar 24, 2021

    I can't imagine this being useful even at an enormous scale unless you're talking about processing millions of threads, and if you're doing that, you presumably have a spare megabyte or two of RAM to cope with it.

    All it really does is obfuscate the code a little. It's an interesting puzzle for people who are learning about algorithms but it has no role in the real world except for that one programmer your friend met one time.

    • Nino Filiu
      Nino FiliuMar 24, 2021

      Defo. I only had to swap variables in exercises in my old uni, and to answer people on stack overflow. Since then I've been in the industry for years and I never had to do that.

    • Edmundo Sanchez
      Edmundo SanchezMar 26, 2021

      It might be some close to metal thing that needs to happen in metofs we use daily.

      I can see the benefit of not needing to reservu, use and clean up some variable, remmber io ooerations are slower than just adding and subtracting.

  • Roman Right
    Roman RightMar 24, 2021

    Hello,
    Nice article and correct algo. But while you are using python here, there is a trick about this. Python supports tuple assignments. it means you can swap the values with just:

    a, b = b, a
    
    Enter fullscreen mode Exit fullscreen mode
    • Nino Filiu
      Nino FiliuMar 24, 2021

      js too

      [a, b] = [b, a]
      
      Enter fullscreen mode Exit fullscreen mode
      • Dan Jones
        Dan JonesMar 26, 2021

        PHP, too.

        [$a, $b] = [$b, $a];
        
        Enter fullscreen mode Exit fullscreen mode
  • thecosmicsound1
    thecosmicsound1Mar 24, 2021

    Interesting algo. Liked the creative approach - can be a good trick interview question. One case where it won't work, for example with ints in Java, a and b are very large ints and summing them would cause an overflow.

  • Roman Right
    Roman RightMar 24, 2021

    Probably you are right. I decided, that it is good to show this too, as Python is in the article's tags.

  • Peko
    PekoMar 25, 2021

    asdasdsad

Add comment