The algorithm XOR swap algorithm
the algorithm typically corresponds 3 machine code instructions. since xor commutative operation, x xor y can replaced y xor x in of lines. when coded in assembly language, commutativity exercised in second line:
in above system/370 assembly code sample, r1 , r2 distinct registers, , each xr operation leaves result in register named in first argument. using x86 assembly, values x , y in registers eax , ebx (respectively), , xor places result of operation in first register.
however, algorithm fails if x , y use same storage location, since value stored in location zeroed out first xor instruction, , remain zero; not swapped . note not same if x , y have same values. trouble comes when x , y use same storage location, in case values must equal. is, if x , y use same storage location, line:
sets x 0 (because x = y x xor y zero) , sets y 0 (since uses same storage location), causing x , y lose original values.
Comments
Post a Comment