This entry is part 2 of 3 in the series algorithms

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.

Anuj holds professional certifications in Google Cloud, AWS as well as certifications in Docker and App Performance Tools such as New Relic. He specializes in Cloud Security, Data Encryption and Container Technologies.

Initial Consultation

Anuj Varma – who has written posts on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.


Series NavigationThe Under-Appreciated Hash Function–Illustrated using a Birthday LookupRecursion versus Iteration ( Looping )