# The XOR Swap

The $XOR$ swap algorithm is a clever programming trick used to swap the values of two variables without using a third temporary variable. This method exploits the properties of the $XOR$ bitwise operation to perform the swap efficiently and in a mathematically elegant manner. The $XOR$, or “exclusive or,” operation on two bits results in a value of 1 if and only if the bits are different; otherwise, the result is 0.

## Algorithm

The algorithm is described as follows:

Expanding this:

When changing the order of operations:

Based on the $XOR$ properties, where we know that $x⊕x=0$ and that $x⊕0=x$, $0⊕x=x$, we arrive at the following conclusions, completing the swap process:

## Practical Example

Suppose we have two numbers we want to swap:

Info

Let $x_{0}$ and $y_{0}$ denote the initial values of variables $x$ and $y$, respectively. Here, the subscript $2$ indicates that the numbers are in base-2 (binary) notation.

Applying the XOR operation on these values:

Continuing with the process:

And finally:

Thus, after applying the $XOR$ swap algorithm, $x_{0}$ (originally $101$) has been swapped with $y_{0}$ (originally $010$), demonstrating the algorithm’s effectiveness with a practical example.