Search code examples
mathlanguage-agnosticswap

What are the different versions of arithmetic swap and why do they work?


I think we all should be familiar of the arithmetic swap algorithm, that swaps two variables without using a third variable. Now I found out that there are two variations of the arithmetic swap. Please consider the following:

Variation 1.

int a = 2;
int b = 3;
a = a + b;
b = a - b;
a = a - b;

Variation 2.

int a = 2;
int b = 3;
b = b - a;
a = a + b;
b = a - b;

I want to know, why are there two distinct variations of the arithmetic swap and why do they work? Are there also other variations of the arithmetic swap that achieve the same result? How are they related? Is there any elegant mathematical formula that justifies why the arithmetic swap works the way it does, for all variations? Is there anything related between these two variations of the two arithmetic swap, like an underlying truth?


Solution

  • Break each variable out as what it represents:

    a = 2
    b = 3
    a1 = a + b
    b1 = a1 - b = (a + b) - b = a
    a2 = a1 - b1 = (a + b) - a = b
    
    a = 2
    b = 3
    b1 = b - a
    a1 = a + b1 = a + (b - a) = b
    b2 = a1 - b1 = b - (b - a) = a
    

    There's not underlying truth other than the fact that the math works out. Remember that each time you do an assignment, it's effectively a new "variable" from the math side.