I am trying to extend xor-swap to more than two variables, for example n variables. But nowhere have I become better than 3*(n-1) .
For two integer variables x1 and x2 you can change them as follows:
swap(x1,x2) { x1 = x1 ^ x2; x2 = x1 ^ x2; x1 = x1 ^ x2; }
So, suppose you have x1 ... xn with values v1 ... vn . It is clear that you can "rotate" the values by applying swap sequentially:
swap(x1,x2); swap(x2,x3); swap(x3,x4); ... swap(xm,xn);
As a result, you get x1 = v2 , x2 = v3 , ..., xn = v1 .
What is the cost of n-1 swaps, each of which costs 3 xors, leaving us with (n-1)*3 xors.
Is a faster algorithm using only xor and assignment and no additional variables are known?
source share