Last active
December 12, 2015 12:38
-
-
Save whymarrh/4773071 to your computer and use it in GitHub Desktop.
The XOR swap algoritm in C.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void swap(int *a, int *b); | |
int main(int argc, char **argv) { | |
int a = 1; | |
int b = 2; | |
swap(&a, &b); | |
return 0; | |
} | |
void swap(int *a, int *b) { | |
/* | |
If the two addresses are the same, the | |
algorithm will simply be `*x = *x ^ *x` | |
three times, which results in zero and | |
the value will be lost. | |
*/ | |
if (a == b) { | |
return; | |
} | |
/* | |
1. *a = *a ^ *b | |
2. *b = *a ^ *b -> (*a ^ *b) ^ *b -> *a ^ (*b ^ *b) -> *a ^ 0 -> *a | |
3. *a = *a ^ *b -> (*a ^ *b) ^ *a -> *b ^ (*a ^ *a) -> *b ^ 0 -> *b | |
*/ | |
*a = *a ^ *b; | |
*b = *a ^ *b; | |
*a = *a ^ *b; | |
} | |
/* | |
As an example, let the variable `a` hold the value 12 and the variable `b` hold the value 7. | |
1. a = a ^ b | |
00001100 | |
^ 00000111 | |
---------- | |
00001011 the current value of a | |
2. b = a ^ b | |
00001011 | |
^ 00000111 | |
---------- | |
00001100 the current value of b | |
3. a = a ^ b | |
00001011 | |
^ 00001100 | |
---------- | |
00000111 the current value of a | |
The swap finishes with `a` getting the value of 7 and `b` getting the value of 12. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment