Saturday, April 28, 2012

Swapping Two Variables

Well, after I get bored from something like this:
function swapTwoVariables(a, b) {
    var temp = a;
    b = a;
    a = temp;
    return [a, b];
}
I decided to recover in my mind how it can be done more nicely.
OK, right now I remember four ways (in pseudocode):
1) old good XOR:
A = 1, B = 9;
A = A xor B;
B = A xor B;
A = A xor B;

2) suppose we have no XOR in our programming language:
A = 1, B = 9;
A -= B += A -= B = -B;

3) probably you know the XCHG command

4) in some modern languages we can do:
[A, B] = [B, A]
Sure, not only Integers can be swapped in such a ways but some other types too.
If you know how to do it some other way, tell me, please.

No comments:

Post a Comment