Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best algorithm for swapping?

Tags:

c

crash

swap

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.

like image 773
Ashish Yadav Avatar asked Mar 13 '10 05:03

Ashish Yadav


People also ask

What is the algorithm for swapping of two numbers?

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.

Why XOR is used for swapping?

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).

Is XOR swap faster?

On modern CPU architectures, the XOR technique can be slower than using a temporary variable to do swapping.


2 Answers

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;

like image 132
Yin Zhu Avatar answered Sep 21 '22 16:09

Yin Zhu


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.

like image 34
caf Avatar answered Sep 20 '22 16:09

caf