Tuesday, January 19, 2010

Swap without temp

A few days back, I was asked by one of my friends to swap the values of two integer variables without using a temp variable. Fortunately, I had seen this problem an year ago and I recalled the one liner code and gave him the ans. After he went away and I was all alone, I started thinking of other methods. I derived two of them pretty quickly. And after some research on the net I found a fourth method as well. So here I'm presenting all the four methods to do the magic. I am also including a C implementation of all four methods.

Let the two variables be 'a' and 'b'.

Method 1: Sum and difference

a=a+b;
b=a-b;
a=a-b;


Method 2: Product and division

a=a*b;
b=a/b;
a=a/b;


Method 3: Three successive bitwise XORs

a=a XOR b;
b=a XOR b;
a=a XOR b;


Method 4: One liner code with double assignment

b=a-b+(a=b);



And here is the C implementation of all the given methods


#include <stdio.h>
#include <process.h>
int main(){
int a, b, c;
printf("Enter the value of 'a':\n");
scanf("%d", &a);
printf("Enter the value of 'b':\n");
scanf("%d", &b);
printf("Enter the method for swapping the values:\n1 for sum method, 2 for product method, 3 for XOR method, 4 for one liner method, anything else to exit.\n");
scanf("%d", &c);
switch(c){
case 1:
a=a+b;
b=a-b;
a=a-b;
printf("You chose method 1. The new values are a=%d and b=%d\nThe algorithm used was:\na=a+b;\nb=a-b;\na=a-b;",a,b);
break;
case 2:
a=a*b;
b=a/b;
a=a/b;
printf("You chose method 2. The new values are a=%d and b=%d\nThe algorithm used was:\na=a*b;\nb=a/b;\na=a/b;",a,b);
break;
case 3:
a=a^b;
b=a^b;
a=a^b;
printf("You chose method 3. The new values are a=%d and b=%d\nThe algorithm used was:\na=a XOR b;\nb=a XOR b;\na=a XOR b;",a,b);
break;
case 4:
b=a-b+(a=b);
printf("You chose method 4. The new values are a=%d and b=%d\nThe algorithm used was: b=a-b+(a=b);",a,b);
break;
default:
exit(0);
}
return (0);
}


The third and the fourth methods are geekier than the previous two. I leave it to you to find out how the third method works.

1 comment:

desidude said...

desidude03.blogspot.com visit it...relli lykd your Bro!!!!!!!!