Advertisemen
I just wanted to see how the XOR swap algorithm works at bit level, the code for the algorithm is:
void xorSwap(int &a,int &b)
{
a=a^b;
b=a^b;
a=a^b;
}
lass="MsoNormal" style="line-height: normal; margin-bottom: 0.0001pt;">Let's do a simple swap of a = 0 and b = 1
a = a^b = 0^1 = 1;
b = a^b = 1^1 = 0;
a = a^b = 1^0 = 1;
b = a^b = 1^1 = 0;
a = a^b = 1^0 = 1;
Now a more complex swap of a = 5 and b = 7
a = 5 = 0b101
b = 7 = 0b111
a = a^b = 101^111 = 010;
b = a^b = 010^111 = 101;
a = a^b = 010^101 = 111;
Advertisemen
Tidak ada komentar:
Posting Komentar