SWAP()
There are three common different versions of SWAP function on the internet.
- SWAP_v1: Need additional space.
- SWAP_v2: May be overflow.
- SWAP_v3: No above risk.
void SWAP_v1(int *a, int*b)
{
int temp; //Need additional space
temp = *a;
*a = *b;
*b = temp;
}
void SWAP_v2(int *a, int*b) //
{
*a = *a + *b; //May be overflow, INT_MAX + INT_MAX
*b = *a - *b;
*a = *a - *b;
}
void SWAP_v3(int *a, int*b)
{
if(*a == *b) //Prevent *a = 0
return;
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}