Swap algorithm without third variable

Swapping is commonly used when we have two variables, and need to make sure if one is greater than another. The most commonly used Swap Algorithm is as below:

Third Variable

void Swap(int& a, int& b){
    int tmp = a;
    a = b;
    b = tmp;

What if, although it’s not really possible, that you have not enough memory for a tmp variable? Now, the following Swap Algorithm comes in handy:

Binary Operation

void Swap(int& a, int& b){
    a = a + b;
    b = a - b;  // b = (a+b) - b
    a = a - b;  // a = (a+b) - [(a+b) - b]

Algorithms has pros and cons too. While using Binary Operation can save you one-variable memory, it is not save to use in data types such as float or double. This is because the round off error while doing the binary operations will destroy the actual value of the variables.

Swap algorithm without third variable

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s