C/swaping
Expert: Zlatko - 2/26/2010
Questionhow to swap 3 no without using 4th no and efficiently
AnswerHello Harshal.
I believe you want to swap 2 numbers without using a third temporary number. The code uses exclusive-or operations.
int main()
{
int a = 0x0F;
int b = 0xF0;
a = a ^ b;
b = a ^ b;
a = a ^ b;
return 0;
}
I don't think this is more or less efficient than using a temporary. Whatever difference there is will not matter. But you can try an exercise if you are using Microsoft Windows. Put this into a loop and do it a few million times. Use the windows QueryPerformanceCounter function to get the CPU counter before and after the loop and see how many ticks the loop takes. Then do a similar test with the temporary variable method. Let me know which one takes fewer ticks.
See
http://msdn.microsoft.com/en-us/library/ms644904%28VS.85%29.aspx
Best regards
Zlatko