I've been trying to extend the xor-swap to more than two variables, say n
variables. But I've gotten nowhere that's better than 3*(n-1)
.
For two integer variables x1
and x2
you can swap them like this:
swap(x1,x2) {
x1 = x1 ^ x2;
x2 = x1 ^ x2;
x1 = x1 ^ x2;
}
So, assume you have x1
... xn
with values v1
... vn
. Clearly you can "rotate" the values by successively applying swap:
swap(x1,x2);
swap(x2,x3);
swap(x3,x4);
...
swap(xm,xn); // with m = n-1
You will end up with x1 = v2
, x2 = v3
, ..., xn = v1
.
Which costs n-1
swaps, each costing 3
xors, leaving us with (n-1)*3
xors.
Is a faster algorithm using xor and assignment only and no additional variables known?