Swap 2 variables without 3rd variable.

November 29, 2006 at 4:30 pm 1 comment

Hey this is quiet interesting in programming.
Typical SWAP functions usually use a 3rd variable to store the value of the one that you want to swap.

Ex:
Given:
X = 10
Y= 20
Result:
X = 20
Y= 10

X = X + Y -> X = 20 + 10 = 30
Y = X - Y -> Y = 30 - 10 = 20
X = X – A –> X = 30 – 20 = 10

You can also do it with the exclusive or bitwise operator

X=(X^=Y)^(Y^=X);

Entry filed under: Algorithm.

The $25,000,000,000 Eigenvector: The Linear Algebra Behind Google

1 Comment Add your own

  • 1. Devendra kumar  |  September 27, 2010 at 3:02 pm

    This amanging trick i like it too

    Reply

Leave a comment

Trackback this post  |  Subscribe to the comments via RSS Feed


Calendar

November 2006
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
27282930  

Most Recent Posts