Learn How to Swap Elements in all Possible Way

Swap refers to the exchange between two or more things.
 

what is swapping?
But it’s a normal business definition. In programming, Swap refers to exchange the values between two or more variable. Now we know what is swapping, but what is the process of swap? Any idea!? Ok, let’s learn it.
 

How to Swap

Imagine that you have two glasses. One is green and one is blue glass. Green and blue glasses are poured with 7-up and mountain-due respectively. Now you have to interchange them without mixing them. That means 7-up has to get into the blue glass and mountain-due has to get into the green glass but they can’t be mixed up. In this case, what would you like to do? If you pour the blue glass mountain-due into green glass then it will be mixed up with 7-up. Same as vice versa. Now, what should we do? Maybe we can use an empty glass to interchange them. A little bit confused!? Ok, let’s try how we can. 
 
How to swap
 
Assume that we have a white empty glass. Now if we pour the green glass 7-up into white empty glass then the white glass will be fully filled with 7-up and the green glass will empty, right? Here we are ready to pour the mountain-due into the green glass. If we pour the mountain-due into the green glass from the blue glass then the blue glass will empty. Now we can easily pour the 7-up into the blue glass from the white glass. Now we have done our operation. See! We have swapped the drinks. It’s too much easy!!. Look at the picture then you will understand more easily.
 
Now we know how to swap anything in real life. Well now try to do it in the programming language. Here we go… 
 

Swap with an extra variable

Temporary_element = First_element;
First_element = Second_element;
Second_element = Temporary_element;
 
Here ‘Temporary_element’ is a temporary variable which will work as the empty white glass. First of all, we pass the First_element value into Temporary_element then we pass the Second_element value into the First_element and finally, we pass the Temporary_element value into Second_element. Here more techniques are given, these you can use for swap.
 

Swap using Arithmetic operation

First_element = First_element + Second_element;
Second_element = First_element – Second_element;
First_element = First_element – Second_element;
 

Swap using bitwise X-OR operation

First_element = First_element ^ Second_element;
Second_element = First_element ^ Second_element;
First_element = First_element ^ Second_element;
 
[Note: Bitwise X-OR operation is fastest way to Swap two variable]
 
Be with us, stay happy. Please do your precious comment and give an opportunity to improve us. Happy coding.
 

November Challenge 2020 SOLUTION CodeChef

October Lunchtime 2020 CodeChef SOLUTIONS

RELATED :

Related :

Related :

Leave a Comment

close
error: Content is protected !!