Search code examples
ccrashswap

best algorithm for swapping?


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.


Solution

  • 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;