Monday 15 August 2016

Anirudh

The many different ways of swapping two numbers

One of the most seen snippets of code is the one that swaps the values of two variables. This little job is crucial to many algorithms, and there are multiple ways of doing it. Generally, for swapping two variables we use a temporary third variable, but various other ways do not even require the help of any third variable.
I find it very interesting that there are so many ways of doing this seemingly simple job and so, I thought to share all the ways I know of swapping two numbers...

1. The simple method using a third variable
#include <stdio.h>
int main()
{
    int a = 10, b = 5, temp;

    // Code to swap a and b:
    temp = a;
    a = b;
    b = temp;

    printf("After swapping: a = %d, b = %d", a, b);
    return 0;
}

Now let's look at some methods which do not require any additional variables.

2. Using arithmetic operators + and -
a = a + b;
b = a - b;
a = a - b;
The above way works well, but it may cause arithmetic overflow when adding large numbers.

3. Using arithmetic operators * and /
a = a * b;
b = a / b;
a = a / b;
This way will not work if one of the numbers is zero, as the product becomes zero. It may also cause arithmetic overflow when multiplying large numbers.

4. Using bitwise XOR operator ^
a = a ^ b;
b = a ^ b;
a = a ^ b;
This method is perhaps a bit more efficient, because it uses bitwise operator only. It can also be written in a more compact manner like this:
a ^= b;
b ^= a;
a ^= b;

Note: When using pointers to the variables, the above methods 2, 3 and 4 will fail if both the pointers point to the same variable. Example: If a function to swap two variables is accepting the addresses of the two variables, then a call like swap(&a, &a); should make no effect on the value of variable a, but in the above methods (except method 1) the variable will store incorrect value. So, we need to firstly check if both the pointers are exactly the same. A good example of using the above swap methods with pointers can be like:
void swap(int *x, int *y)
{
    if(x != y)    // Checking that x and y are not pointing to the same location
    {
        *x ^= *y;
        *y ^= *x;
        *x ^= *y;
    }
}

5. Using bitwise XOR operator ^ in one line
a ^= b ^= a ^= b;
This is similar to method 4 but three statements have been compounded into one. Order of evaluation is from right to left.

6. Using arithmetic operators + and - in one line
a = (a + b) - (b = a);
The problem of arithmetic overflow can occur in this method.

7. Using arithmetic operators * and / in one line
a = (a * b) / (b = a);
The problem of arithmetic overflow can occur in this method. Also, it will show undefined behavior if the first number a = 0 (because that will lead to division by zero).

8. Using arithmetic operators + and - in a slightly different way
a = b - a;
b = b - a;
a = b + a;
Note that the corresponding method with * and / operators does not work.

Note: The methods 5, 6, 7 and 8 also work well when using pointers to the variables. But methods 5 and 8 will give wrong result if the pointers point to the same location.

9. Using a file as buffer
FILE *fp;

fprintf(fp = fopen("temp.txt", "w"), "%d", a);
fclose(fp);
a = b;
fscanf(fp = fopen("temp.txt", "r"), "%d", &b);
fclose(fp);
Of course, using such a method incurs a lot more overhead than the usual methods. Just included for theoretical purposes.

10. Using a command-line-related variable as buffer
int main(int argc, char **argv)
{
    int a = 10, b = 5;

    argc = a;
    a = b;
    b = argc;

    printf("After swapping: a = %d, b = %d", a, b);
    return 0;
}

11. Using a macro
#define SWAP(x, y, Type) Type temp = x; x = y; y = temp;

int main()
{
    int a = 10, b = 5;

    SWAP(a, b, int);

    printf("After swapping: a = %d, b = %d", a, b);
    return 0;
}
Its advantage is that it is generic up to some extent. The same SWAP macro will work for types like int, float and char. By using this GCC-specific extension, we can improve it further like:
#define SWAP(x, y) typeof(x) temp = x; x = y; y = temp;
The problem with method 11 will arise when there is already a variable named temp in the program!

Anirudh

About the author →

Anirudh Khanna is a Computer Science student and a geek who firmly believes in the awesomeness of technology! He is a programmer and web designer, also keenly interested in the research of new and innovative ideas in Computer Science.

Subscribe to Geek Factorial via email :

1 comments

Write comments
Anonymous
AUTHOR
November 30, 2022 2:35 pm delete

It's so helpful Anirudh Khanna.

Reply
avatar