Thursday, October 1, 2020

變數互換|四種 swap

內容目錄

Simple Swap

Swap by Pointer

Swap by XOR (Bitwise Operation)

Swap by Macro

Simple Swap

1
2
3
4
5
void swap(int a, int b){
    int tmp = a;
    a = b;
    b = tmp;
}

Swap by Pointer

1
2
3
4
5
void swap(int *a, int *b){
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

Swap by XOR (Bitwise Operation)

XOR 可以做為最基本的加密方法,因為他有這個特性:做兩次一樣的運算等於沒做。

所以 A xor B 經過傳輸以後,解密 ( A xor B ) xor B = A;

知道這個特性就可以用 xor 做交換了

A xor B xor A = B
B xor B xor A = A

1
2
3
4
5
6
7
void XorSwap( int* x, int* y ) {
    if (x != y){
        *x ^= *y;
        *y ^= *x;
        *x ^= *y;
    }
}

Swap by Macro

1
2
3
4
#define SWAP(x, y) \
    int tmp = x;\
    x = y;\
    y = tmp;

以及和第一個方法很樣的:
Horowitz的Fundamentals of Data Structures in C一書中使用的。

1
#define SWAP(x, y, t) ((t) = (x), (x) = (y), (y) = (t))

No comments:

Post a Comment

n8n index

 【n8n免費本地端部署】Windows版|程式安裝x指令大補帖  【一鍵安裝 n8n】圖文教學,獲得無限額度自動化工具&限時免費升級企業版功能