9月 20, 2009

藉由 XOR 運算來實現 swap 功能

Keyword:XOR swap algorithm

這真是一個非常 tricky 的方法,藉由 XOR 運算就能將兩值互換。輸入的格式不限,包含 int、char 均可。
#define  swap(X, Y)  (X^=Y, Y^=X, X^=Y)
注意:當輸入兩相同運算元(operator)時,其運算結果會為零。
swap(X,X),則 X 結果為零。
當 X=10, Y=10, swap(X,Y) 結果會是正常 X=10, Y=10。
另外這種用法不具可攜性(portably),有些編譯器會錯誤解讀,造成運算結果與預期不同。而且效能會比一般三個 assign operation 的方法來的慢。因為指令間具有相依性,所以無法進行 pipeline 處理。
XOR technique is considerably slower than using a temporary variable to do swapping. One reason is that modern CPUs strive to execute commands in parallel. In the XOR technique, the inputs to each operation depend on the results of the previous operation.
演算法的理論基礎:
定理:
反元素 A^A = 0
交換性 A^B = B^A
結合性 (A^B)^C = A^(B^C)
單位元 A^0 = A

推導:
A = A ^ B
B = A ^ B = (A^B) ^ B = A ^ (B^B) = A^0 = A
A = A ^ B = (A^B) ^ A = (B^A) ^ A = B

沒有留言:

張貼留言