Swap Values, no third variable

A classic problem asked in many interviews and such. And almost every genius will tell you that its simple.

swap(int *x,int *y)
{
  *x += *y;
  *y = *x - *y;
  *x = *x - *y;
}

Simple right? Wrong!
what happens if one value is 2147483647 and the other is 2147483640 ?
You will definitely overflow x and make a mess of it!

So whats the foolproof way?  Observe!

swap(int *x, int *y)
{
 *x ^= *y;
 *y ^= *x;
 *x ^= *y;
}

So how is it done? Bit-wise Xor operation. Faster, better and guaranteed to get you laid. For more info on bit wise xor Google it or click here

Technorati Tags: , ,

Advertisements

One thought on “Swap Values, no third variable

  1. Hey BIT MASTER…i dont see the need for ANDing the mask>>=1 value with -1 in the while loop…can u plz explain?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s