Friday, May 29, 2009

Swapping 2 Integers

I believe many of us out there came across, at least once in their lifetime, the problem to swap two numbers. Here are the three sample solutions that I could think to swap two numbers.
Solution A:

temp = a;
a = b;
b = temp;
Solution A introduces an additional auxiliary variable called "temp" in the code to hold one of the values (either a or b) which increases the footprint of the compiled class.
Solution B:

a = a ^ b;
b = b ^ a;
a = a ^ b;
Solution B on the other side swaps two numbers using bitwise operation. The XOR (Exclusive OR) is introduced in this code.
Solution C:

a = a + b;
b = a - b;
a = a - b;
Last but not least, Solution C swaps two numbers using arithmetic operations, both addition and subtraction.
Conclusion: In terms of speed, I would personally rank Solution B being the fastest, Solution C the second fastest and Solution A the slowest. (B -> C -> A)

0 comments:

Post a Comment