Swapping of two numbers with or without using third variable


Have you ever been asked to swap two variables programetically. There could be variable approach but this article highlights two simplest possible way for you. try this algo in any of your favourite language.

Swapping two numbers is one of the common programs which we are given in schools and Colleges when we first learn to write programs. There could be different approaches which we can use to make this possible. Here as I am putting this article in general programming category I will not write a program but an algorithm for this programming problem.

Let us observe the simpler approach first, with the use of third variable:


/*
This algorithm is intended to show how to swap two numbers.
The assumption is made that the functions defined in this program can access the global variables somehow.
*/
//declare two variables
define var1;
define var2;

//get input from user
var1 = getInput();
var2= getInput();

//print the numbers before swapping
printVars();

//swap the numbers
swapVars();

//print the numbers after swapping
printVars();

/*define the utility functions for the programming*/
//function to take user input
define function getInput(){
	//prompt user for input
	output: "please, enter a value";
	
	//get value and return
	return userInput;
}

//function to print values
define function printVars(){
	//+ sign denotes the concatination
	output: "value of var1 is:"+var1;
	output: "value of var2 is:"+var2;
}

//function to swap the numbers
define function swapVars(){
	define locVar;
	locVar = var1;
	var1 = var2;
	var2 = locVar;
}

This program is possibly the simplest logic for the purpose here is what it does:

var1 = 2;
var2 = 4;
locVar(2) = var1(2);
var1(4) = var2(4);
var2(2) = locVar(2);

Considering this algo suppose we need to write a program to not use the third variable in the function. we can re-write the function swapVars as follows:


define function swapVars(){
	var1 = var1+var2;
	var2 = var1 - var2;
	var1 = var1 - var2;	
}

I guess this one is also simple. but this saves the use of local variable. However this does not make much of the difference in terms of performance but it saves time in doing allocation and de-allocation for the local variable. And as the addition is very basic part and is supported at hardware level this is definitely fast. Following steps occurs while the swap function is called:

var1 = 5
var2 = 6
var1(11) = var1(5) + var2(6)
var2(5) = var1(11) - var2(6)
var1(6) = var1(11) - var2(5)

Note: This look pretty simple but I still recommend that you try to implement this in your favourite programming language.