You are here:

C/swaping

Advertisement


Question
how to swap 3 no without using 4th no  and efficiently

Answer
Hello 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

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.