60 subscribers








  |  Technology  |  Science Stuff  |  Travel  |  Bollywood  |  Buddhism  |  Finance and Investing  |  Austin  |  India  |  Diet, Health  |  Petitions, Causes  |  

Posted on by Anuj Varma
Swapping without a temp variable

Everyone is familiar with the basic swap – using a temporary variable

 static void RegularSwapUsingTempVariable(ref int a, ref int b)
 {
           int temp = a;
           a = b;
           b = temp;
 }

The same swap can be done without the use of a temporary variable.  One needs to simply store the differences of the two values in each variable – and use a simple algorithms as shown below:

static void SwapWithoutTempVariable(ref int a, ref int b)
      {
          // first, set a to the difference a-b
          a = a - b;
          // next, add b to the difference - thereby being left with a
          b = a + b;
          // now remove a from the original difference - leaving just b
          a = b - a;
      }

Summary

Next time you want to stump someone, ask them to write a simple swap. Chances are 100% that they will use a temporary variable to write it. Now, ask them to write it without using any temporary variable.

Recent Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

*