Problem
Write a function to swap two number in place without temporary variables.
Solution
Method1 - The XOR or Exclusive trick
In C this should work:
a ^= b ^= a ^= b;
to simplify :
a=a^b; b=a^b; a=a^b;
OR
a^=b; b^=a; a^=b;
Following are operations in XOR
- 0^0=0
- 0^1=1
- 1^0=1
- 1^1=0
Hence, we have:
- a=a^b: 'a' will save all the bits that a differs from b: if the bit that 'a' and 'b' differ, it gets 1, otherwise 0.
- b=a^b: 'b' will compare to the difference between a and b: for the bit that 'b' and 'a' differ, it means a have 1 at this position and the result of a^b will assign that bit to 1; for the bit that 'b' and 'a' agree, it means a have 0 at this position and the result of a^b will assign that bit to 0.
- a=a^b: same logic
Now, if suppose, by mistake, your code passes the pointer to the same variable to this function. Guess what happens? Since Xor'ing an element with itself sets the variable to zero, this routine will end up setting the variable to zero (ideally it should have swapped the variable with itself). This scenario is quite possible in sorting algorithms which sometimes try to swap a variable with itself (maybe due to some small, but not so fatal coding error). One solution to this problem is to check if the numbers to be swapped are already equal to each other.
swap(int *a, int *b) { if(*a!=*b) { *a ^= *b ^= *a ^= *b; } }
Method 2 - Simple addition and subtraction
This method is also quite popular
a=a+b; b=a-b; a=a-b;
OR
a =((a = a + b) - (b = a - b));But, note that here also, if a and b are big and their addition is bigger than the size of an int, even this might end up giving you wrong results.
0 comments:
Post a Comment