65.9K
CodeProject is changing. Read more.
Home

Cost Reduced Swap

starIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

1.00/5 (14 votes)

Dec 9, 2006

viewsIcon

36050

Swapping in C++

Introduction

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.