best algorithm for swapping?

10,235

Solution 1

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;

Solution 2

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.

Solution 3

See http://en.wikipedia.org/wiki/Swap_(computer_science) .

Using a temporary variable generates more overhead, but is more stable than the XOR swap algorithm and parallel computing renders it faster than XOR swap.

See the first code example of http://www.ibm.com/developerworks/linux/library/l-metaprog1.html for a solid implementation of using a temporary variable for swapping.

Share:
10,235
Ashish Yadav
Author by

Ashish Yadav

I am a CS graduate from National Institute of Technology , Patna , India . I like programming in C and C++ with special interests in Designing efficient data structures and algorithms. I am a Member of Technical Staff at NetApp Contacts: [email protected] [email protected] [email protected] [email protected]

Updated on June 04, 2022

Comments

  • Ashish Yadav
    Ashish Yadav almost 2 years

    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.