i have heard from a friend of mine that the best algorithm for swapping is " (a^=b^=a^=b)" where a and b are two integers to be swapped. but when i applied this using c language it resulted in crashing. can anyone of you fine people explain the possible reason for that? please suggest the best algorithm for swapping. thank you!!!! guys i would like to know the reason for crashing.
Example: Suppose, there are two numbers 25 and 23. X= 25 (First number), Y= 23 (second number) Swapping Logic: X = X + Y = 25 +23 = 48 Y = X - Y = 48 - 23 = 25 X = X -Y = 48 - 25 = 23 and the numbers are swapped as X =23 and Y =25.
The bitwise XOR operator can be used to swap two variables. The XOR of two numbers x and y returns a number that has all the bits as 1 wherever bits of x and y differ. For example, XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111, and XOR of 7 (0111) and 5 (0101) is (0010).
On modern CPU architectures, the XOR technique can be slower than using a temporary variable to do swapping.
this swapping trick is sometimes dangerous, I have seen a a wrong quicksort program using this swap generates wrong results. But a usual swap generates correct program.
Respect to speed, the compiler sometimes generates faster code if we use a tmp variable.
use tmp = a; a = b; b = tmp;
a^=b^=a^=b;
probably crashes because it invokes the dreaded undefined behaviour. The rule it breaks is that it modifies a
twice without an intervening sequence point. It can be fixed by inserting some sequence points - for example, with the comma operator:
a ^= (b ^= a ^= b, b);`
Or by breaking it up into multiple statements:
b ^= a ^= b; a ^= b;
It is still, however, usually a bad method for swapping variables - several of the other answers and comments have adequately explained why.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With