Best exchange algorithm?

I heard from my friend that the best algorithm for the exchange is "(a ^ = b ^ = a ^ = b)" where a and b are two integers to be exchanged. but when I applied it using c, it led to a crash. can any of you wonderful people explain the possible reason for this? suggest the best algorithm for sharing. Thanks!!!! guys, I would like to know the reason for the failure.

+5
source share
5 answers

this exchange trick is sometimes dangerous, I saw the wrong quicksort program using this swap, generating incorrect results. But a regular swap generates the right program.

, , tmp.

tmp = a; a = b; b = tmp;

+9

a^=b^=a^=b; , , undefined. , , , a . , - , :

a ^= (b ^= a ^= b, b);`

:

b ^= a ^= b; a ^= b;

-, , - , .

+10

, . . , , . XOR-, , .

0

:

    int a = 10, b =5 ;
    a = a-b;
    b = b+a ;         // b gets the original value of a
    a = b - a;    // a gets the original value of b
    printf ("value : %d %d \n",a ,b) ;
-2

All Articles