by dragontamer · 4y ago · 0 comments
Warning: if x == y, then instead of swapping, the two values are set to zero.
So this swapping trick works only for x!=y.
---------
The other tricks are interesting, and likely hold the key to some kind of parallel programming trick, as a sequence of XORs is trivially parallelizable through the prefix-sum pattern.
All of the other tricks are O(n) number of XOR operations, while parallel prefix-sum is O(log(n)) depth and O(n) total work.
Huh, what?
The issue is:
void xor_swap(int& x, int& y){
x ^= y;
y ^= x;
x ^= y;
}
The issue is *aliasing*. If the pointer &x == &y, then everything goes to crap. When the pointers alias to themselves, the function degenerates into: x ^= x;
x ^= x;
x ^= x;
Which sets x (and the y value) to zero.In contrast:
void regular_swap(int& x, int& y){
int tmp = x;
x = y;
y = tmp;
}
This always works, even with aliasing.