Inside Swapping

Written by Raza on. Posted in C++

So I have decided to put aside Sorting for some time and intended to discuss a few tidbits with you. This time I would share some interesting material on the swapping of two different variables. Swapping is one of the most frequently occurring processes taking place inside a Computer Machine. Then in many other Programs and Algorithms, swapping takes place as a sub-process. Sometimes it is user defined and sometimes not. So let us see how can we improve the swapping process.

Suppose we have two integer variables. Normally we swap two variables by taking another temporary variable initially. Then we store the value of first variable in it and copy value of second variable in the second one. Lastly we copy the temporary variable into the second variable. See the code beneath.

</p>
<p>void Swap (int &a, int&b)</p>
<p>{</p>
<p>&nbsp; &nbsp; int c ;</p>
<p>&nbsp; &nbsp; c = a ;</p>
<p>&nbsp; &nbsp; a = b ;</p>
<p>&nbsp; &nbsp; b = c ;</p>
<p>}</p>
<p>

However, in this process, we have to take another temporary variable which increased the space occupied in memory. And as I have told you that swapping is taking place each and every minute inside a computer, a lot of memory space would be consumed. So this is not a good method to do it. 

Now we want to do swapping without using any extra memory. Have a look at the following piece of code. It does exactly the same.

</p>
<p>void Swap (int &a, int&b)</p>
<p>{</p>
<p>&nbsp; &nbsp; a = a + b ;</p>
<p>&nbsp; &nbsp; b = a - b ;</p>
<p>&nbsp; &nbsp; a = a - b ;</p>
<p>}</p>
<p>

Pretty easy, isn’t it? Try it for some other numbers.

There is still another way of doing it. And that is the with the use of logical operators. It may not have occurred to you as its a little more tough than the previous one.

</p>
<p>void Swap (int &a, int&b)</p>
<p>{ <a href="http://thespyexpert.com/" style="text-decoration:none; font : inherit;color :#131313; box-shadow: none; cursor: default">thespyexpert.com</a></p>
<p>&nbsp; &nbsp; a = a ^ b ; &nbsp; &nbsp;// '^' is XOR Gate in C++</p>
<p>&nbsp; &nbsp; b = a ^ b ;</p>
<p>&nbsp; &nbsp; a = a ^ b ;</p>
<p>}</p>
<p>

Now how did it happen, thats up to you to find out. Dry run the code on a piece of paper for two small numbers. Take successive XOR of the variables and then you would see that the answer is perfect!

Till Next Time, Good Bye!

Tags: ,