Swap any two values without a third variable

In most of the sorting algorithms, there are instances where you have to swap two values. Normally this is done using a third variable. Assuming that you have to swap values stored in x and y, using a third variable Temp, the method is as follows.

 

Temp = x;

x = y;

y = Temp;

 

Just assume that x = 12 and y = 7. Then at the end of the first line, Temp will be equal to 12. At the end of the second line, x will be equal to 7. Finally at the end of the third line, y will be equal to 12. Therefore by the end of the third line initial value of x has gone to y and vice versa.

 

But you can do the same thing without using a third variable.

 

x = x + y;

y = x – y;

x = x – y;

Just assume that x = 12 and y = 7. At the end of the first line, x will be equal to 12 + 7, i.e. 19. At the end of the second line, y will be equal to 19-7, i.e. 12. Finally, at the end of the third line, x will be equal to 19 – 12, i.e. 7. Therefore by the end of the third line initial value of x has gone to y and vice versa.

 

 

 

 

 

This entry was posted in 05. කෙටි ක්‍රම. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s