Swapping without a temp variable
- The Under-Appreciated Hash Function–Illustrated using a Birthday Lookup
- Swapping without a temp variable
- Recursion versus Iteration ( Looping )
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.
Leave a Reply