02 October 2009

How to swap variables without using another space?

This is a very common interview question which is very useful for practical programming paradigm.
void swap (int &i, int &j) {
i = i ^ j;
j = j ^ i;
i = i ^ j;
}
Or define a MACRO:
#define SWAP(i, j) (((i) ^= (j)), ((j) ^= (i)), ((i) ^= (j)))

No comments: