Try   HackMD

交換兩個變數中的值 swap()

變數在儲存資料的時候,我們可以把變數想像為一個容器,而容器以外的空間完全沒有辦法儲存資料。所以在交換倆變數的值時,兩個變數是不夠的,必須得有第三個變數來儲存資料。

解說

而交換兩個變數的值,就好比要交換兩個杯子不同顏色的水,其中 A 杯子裝有紅色的水,B 杯子裝有藍色的水。

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

我們沒有辦法冒然的將 A 的水倒進 B 裡面,再將 B 的水倒進 A 裡面,這會導致兩個杯子的水都是紫色的。

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

因為在把 A 的水倒進 B 裡面時,水的顏色就混和成紫色了,無法達成交換兩杯子水的目的。

這時我們就可以拿第三個杯子 T 出來,先將 A 的水倒進 T 中。

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

此時 A 已經是空杯子了,再將 B 的水倒進 A 中。

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

這時候換 B 成為了空杯子,最後再將 T 的水倒進 B 裡面,A、B 兩杯子的水就互換了。

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

一般情況

而我們在撰寫程式碼的時候可以選擇這樣寫

#include <stdio.h>

int main(){
    int a = 10;
    int b = 15;
    
    // ... do something
    
    // here to swap
    int t = a;
    a = b;
    b = t;
    // complete swap
    
    return 0;
}

函式寫法

# include <stdio.h>

void swap(int *a, int *b){
    int t=*a;
    *a = *b;
    *b = t;
}

int main(){
    int a = 10;
    int b = 15;
    
    // ... do something
    
    // here to swap
    swap(&a, &b);
    // complete swap
    
    return 0;
}

XOR swap

#define swap(a, b) (a^=b, b^=a, a^=b)

證明

a=abb=ba=b(ab)=aa=ab=(ab)a=b

總結

上述任何方式都可以交換兩個變數的值,在經過編譯器最佳化過後,都會變成 XOR swap 所以要用哪個其時效能都差不多。