Swapping two variables without using a third

I came across an interesting algorithm ... the normal way how programmers swap values between two variables is by using a temporary third variable ... temp = x, x = y, y = temp. An interesting trick can actually do the same process without having to use a third variable, and this is done by using the XOR operator. Below I am showing how this can be done in java:


public static void main(String[] args) {
int x = 15;
int y = 20;
System.out.println(x+" "+y);
x ^= y;
y ^= x;
x ^= y;
System.out.println(x+" "+y);
}


Try it out !

Comments

Andre Genovese said…
Aw Vince,

just stumbled upon your blog - the variable-swapping algorithm is interesting!

Have been thinking about converting to bloggism myself...I just need a little nudge :)

See you, Andre