Monday, April 11, 2005

Swapping and temporaries

Has anyone ever asked you this? "swap two integers without using temporary variables".
Well, here is the answer that most people give


a = a^b;

b = a^b;

a = a^b;



where 'a' and 'b' are the variables to be swapped.
Lets look at the traditional approach for swapping two variables


inline

swap(long *a, long *b)

{

int tmp = *a;

*a = *b;

*b = tmp;

}


The second version and the first version both use three "C" statements to swap.
The first version will not work for non-scalar types. It will work only for integers, longs, characters and other integral types (called scalars). The second version is easier to maintain and can be extended to cover other types (using templates for example).

On some architectures a = a^b, a^b is stores the result in a temporary and then assigned to 'a'.

Comments?

1 comment:

Gops said...

TSTS (Too Stunned To Speak - BTW, I am patenting this one :) )

Ranking and Unranking permutations

I've been a big fan of Skiena's Algorithm Design Manual , I recently found my first edition of the book (although I own the third ed...