Swap Two Variables in Place
Usually, when a programmer is asked to swap two variables, they will:
- Create a
tempvariable to hold one of their values.temp = x - Assign one to the other
x = y - Retrieve temporary variable
y = temp
What if you were asked to do without adding a temp variable (i.e. without using any extra space). There is two easy ways to so.
The first way uses addition and subtraction. Here is a java implementation of this method.
public static void swap(int x, int y) {
x = y - x;
y = y - x;
x = x + y;
}
The second way uses the XOR operator. With 3 XOR operations, you can swap values in x and y easily.
public static void XORSwap(int x, int y) {
x = x ^ y;
y = x ^ y;
x = x ^ y;
}