algorithmswap

Swapping two numbers using only two variables


How is it performing swapping?

a=a+b
b=a+b
a=b+a

I don't agree that it's swap to a book!!!

The book options include "complements of values of a and b", "negate and b". Hope these options aren't satisfying it too???


Solution

  • The swap is performed using XOR, which is typically written as a plus within a circle (⊕); for example:

    a := 5
    b := 7
    
    a := a xor b (2)
    b := a xor b (5)
    a := b xor a (7)