The XOR Swap

The 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 bitwise operation to perform the swap efficiently and in a mathematically elegant manner. The , 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 properties, where we know that and that , , we arrive at the following conclusions, completing the swap process:

Practical Example

Suppose we have two numbers we want to swap:

Info

Let and denote the initial values of variables and , respectively. Here, the subscript 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 swap algorithm, (originally ) has been swapped with (originally ), demonstrating the algorithm’s effectiveness with a practical example.