Wednesday, May 1, 2013

Swap without using a third variable

We know how to swap 2 values using a third temp variable. This is how you do it without using a third variable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include "stdio.h"

static void swap(int *x, int *y)
{
        *x = *x + *y;
        *y = *x - *y;
        *x = *x - *y;
        return;
}

static void swap_xor(int *x, int *y)
{
        *x = *x ^ *y;
        *y = *x ^ *y;
        *x = *x ^ *y;
        return;
}

int main(int argc, char **argv)
{

        int x = 10, y = 20;
        printf("1> %d %d\n", x, y);
        swap(&x, &y);
        printf("2> %d %d\n", x, y);
        swap_xor(&x, &y);
        printf("3> %d %d\n", x, y);

        return 0;
}

[root@Imperfecto_1 ~]# gcc -g run.c && ./a.out
1> 10 20
2> 20 10
3> 10 20

No comments:

Post a Comment