C/C++
Algorithm
Data Structure
UVA Hints
UVA Problem Ranking
Tip and Trick



 

 
Swapping 2 integers


There are 3 ways to swap 2 integers, the most common one is to use temporary variable. Other ways are to use bit manipulation and math.

Temporary Variable

void swap(int *i,int *j)
{
int tmp = *i;
*i = *j;
*j = tmp;
}

Bit Manipulation

void swap(int *i,int *j)
{
     *i ^= *j;
     *j ^= *i;
     *i ^= *j;
}

N.B.:
i ^= j means i = i XOR j (XOR = eXclusive OR)
Don't try to swap the same variable (i.e. swap(&a,&a) ), it will produce incorrect result

Math

void swap(int *i,int *j)
{
     *i = *i + *j;
     *j = *i - *j;
     *i = *i - *j;
}






     
Copyright © 2004 - Harvest Software