xor swap

The operation xor has dual functions,
as opposite checker or as conditional flipper.
a b | xor
---------
0 0 | 0
0 1 | 1
1 0 | 1
1 1 | 0
So, a fast swap method can be done by
# produce a flag indicating whether
# the two are opposite (1) or equal (0)
a' = a xor b
# re-create a based on flag and orig b, and store it in b
b = a' xor b
# re-create b based on flag and orig a, and store it in a
a = a' xor b
After statement 1, the orig a is no longer in use.
So, in practice, to be more space-saving, use a for a'
a = a xor b
b = a xor b
a = a xor b
何以名之?姑名之曰:三儍對調法.
xor swap 雖然工巧, 但對於當代的 CPU 而言,
標準的 temp swap 不涉及運算, 比它更為迅速, .
tmp = a
a = b
b = tmp
編碼用意也更為明確.

0 Comments:
:: Kommentar veröffentlichen
(留言請留名, 謝!)
<< Home