Блог пользователя sebi

Автор sebi, 16 лет назад, По-английски

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?

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

16 лет назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится
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 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится
> What is your favourite algorithm for swapping variables?

     t = x;
     x = y;
     y = t;
16 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

+/- "solution" leads us to integer overflow. Really, best solution is swapping with temporary variable, and variant a ^= b ^= a ^= b (which have undefined behavior following C standard) is useful only when you have been taken interview for your new work, and have got task "swap two variables without using additional memory).

Also, good variant is std::swap. You code will be at least - readable.

16 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится
if x, y - int, double ... swap(x,y) :)
else 
p = x;
x = y; 
y = t;
16 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится
if x, y - int, double ... swap(x,y) :)
else
p = x;
x = y;
y = t;
16 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится
Where are you from, lad?
16 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится
a, b = b, a