RSS

How will you swap two variable

Fri, Mar 5, 2010

Algorithm

Method1) Using temporary variable
         temp=a;
         a=b;
         b=temp
 
 

Method2 ) Using Macro
#define swap(type,a,b) type temp;  temp=a; a=b; b=temp;
 
 

Method3) Using add/subtract
         a=a+b;
         b=a-b;
         a=a+b;
 
 
Method4) Using Multiplication/division
         a=a*b;
         b=a/b;
         a=a/b;
 
 
Method5) Using XOR method
         a=a^b;
         b=a^b;
         a=a^b;
 
 
Method6) Wrong!! Because evaluation of expression can not be guesses
         a=a+b-b=a;

Sharing ~ Helping Other:
  • Print
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • BlinkList
  • DZone
  • Slashdot
  • YahooMyWeb
  • StumbleUpon
  • Live
  • IndianPad
  • DotNetKicks
  • Technorati

Other Posts:

This post was written by:

eXclusiveMinds - who has written 500 posts on eXclusiveMinds.


Contact the author

Leave a Reply

You must be logged in to post a comment.