Monday, October 7, 2013

Swapping values without using any other variables

Swapping values between 2 variables

   Before swap:
       a=1;
       b=2;

   After swap:
       a=2;
       b=1;


0. Usual way: Using a temporary variable to store value of one variable before replacing its value.
       temp=a;
       a=b;
       b=temp;


Without using any other variables

1. Using XOR or Exclusive Or (^)
       a=a^b;
       b=b^a;
       a=a^b;
   
    Can also be written as:
       a^=b;
       b^=a;
       a^=b;

       Note: Best method (so far) as it uses only the amount of bits that it has. No worry of overflow.

2. Using Addition (+) and Subtraction (-)
       a=a+b;
       b=a-b;
       a=a-b;
   
       Can also be written as:
       a+=b;
       b=a-b;
       a-=b;
   
       Note: Possibility of overflow if any of the value is near maximum.


3. Using Multiplication (*) and Division (/)
       a=a*b;
       b=a/b;
       a=a/b;

       Can also be written as:
       a*=b;
       b=a/b;
       a/=b;

       Note:
           1. Will not work if any of the value is 0 (zero). 
           2. Possibility of overflow if any of the value is near maximum.

You can try them all online here: http://repl.it/languages/JavaScript