Encyclopedia > Xor swap algorithm

  Article Content

Xor swap algorithm

Xor swap is a simple algorithm which uses the Exclusive disjunction (XOR) operation to swap the values of two variables without using an extra variable. This algorithm follows (where X and Y are the names of two variables, rather than two values):

  1. XOR the values of X and Y and store the result in X
  2. XOR the values of X and Y and store the result in Y
  3. XOR the values of X and Y and store the result in X

To see how this works, call the initial value of X = x0 and the initial value of Y = y0. Then:

  • after step 1, X = x0 XOR y0, Y = y0
  • after step 2, X = x0 XOR y0, Y = x0 XOR y0 XOR y0 = x0
  • after step 3, X = x0 XOR y0 XOR x0 = y0, Y = x0

This algorithm varies from other swap algorithms only in that it doesn't need to store the original value of X in a temporary buffer prior to overwriting it and doesn't need to restore this value in Y.

See: Assembler code, Visual Basic code, C code



All Wikipedia text is available under the terms of the GNU Free Documentation License

 
  Search Encyclopedia

Search over one million articles, find something about almost anything!
 
 
  
  Featured Article
Wheatley Heights, New York

... out with 30.3% under the age of 18, 8.1% from 18 to 24, 29.9% from 25 to 44, 23.8% from 45 to 64, and 7.9% who are 65 years of age or older. The median age is 35 years. ...

 
 
 
This page was created in 37 ms