sebi's blog

By sebi, 16 years ago, In English

Suppose you have two variables x and y and you want to swap their values. The usual way to do this is using another temporary variable:

     temp = x;
     x = y;
     y = temp;

However, the interchange of two variables can be done without the temp variable:

     x = x + y;
     y = x - y;
     x = x - y;


What is your favourite algorithm for swapping variables?

  • Vote: I like it
  • 0
  • Vote: I do not like it

| Write comment?
16 years ago, hide # |
 
Vote: I like it +3 Vote: I do not like it
Another alternative (if x and y don't share the same memory, as in the +/- case) is
x ^= y ^= x ^= y;
though this exact wording is not recommended.
  • 16 years ago, hide # ^ |
     
    Vote: I like it +5 Vote: I do not like it

    it is do not work in java. this code in C++.


    • 16 years ago, hide # ^ |
       
      Vote: I like it 0 Vote: I do not like it
      Yes, it doesn't work, because the expression is being calculated from left to right, so the first instance of variable x has the same value as it was before that line, despite of that logic says that it should be changed before we can do first XOR.
16 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it
> What is your favourite algorithm for swapping variables?

     t = x;
     x = y;
     y = t;
16 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it
if x, y - int, double ... swap(x,y) :)
else
p = x;
x = y;
y = t;
16 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it
Where are you from, lad?
16 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it
a, b = b, a