Click here to Skip to main content
15,880,392 members
Articles / Programming Languages / C++
Article

Cost Reduced Swap

Rate me:
Please Sign up or sign in to vote.
1.00/5 (15 votes)
8 Dec 2006 35.1K   11   12
Swapping in C++

Introduction

C++
void main() 
{ 
    int i=10,j=20; 
    j=i+j-(i=j); 
} 

Here the two variables are swapped in a single statement . The cost is reduced than the known swapping methods.

  • Temporary variables are not used.
  • addition and subtraction only.
  • can be used for any data types and this is efficient than the normal methods.
  • time is saved.
  • space is saved.
  • complexity reduced.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
India India
i am an Computer Engineering student from india

Comments and Discussions

 
GeneralTradeoff between efficiency and maintainability Pin
Harold Bamford12-Dec-06 7:46
Harold Bamford12-Dec-06 7:46 
Questionwhat about asm ? Pin
bruno leclerc11-Dec-06 22:35
bruno leclerc11-Dec-06 22:35 
Questionwhat about asm ? Pin
bruno leclerc11-Dec-06 22:33
bruno leclerc11-Dec-06 22:33 
GeneralThe "classic" way Pin
Luca Piccarreta11-Dec-06 3:49
Luca Piccarreta11-Dec-06 3:49 
GeneralNot Guaranteed to Work Pin
ricecake11-Dec-06 3:23
ricecake11-Dec-06 3:23 
Generalexpression is evaluated from left to right Pin
jeyakumarrr10-Dec-06 23:24
jeyakumarrr10-Dec-06 23:24 
Generalit will work in Turbo C& C++ compiler only Pin
jeyakumarrr10-Dec-06 23:23
jeyakumarrr10-Dec-06 23:23 
GeneralDoes not work! Pin
z33z10-Dec-06 6:29
z33z10-Dec-06 6:29 
Generalit will work for all data types.. Pin
jeyakumarrr9-Dec-06 22:48
jeyakumarrr9-Dec-06 22:48 
Generalcheck it out in the system and say Pin
jeyakumarrr9-Dec-06 22:42
jeyakumarrr9-Dec-06 22:42 
QuestionUndefined behaviour? Pin
david_dawkins9-Dec-06 14:22
david_dawkins9-Dec-06 14:22 
GeneralIt doesn't work Pin
Vindicator6669-Dec-06 3:45
Vindicator6669-Dec-06 3:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.