#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void swap1(int &a,int &b){
a=a^b;
b=a^b;
a=a^b;
}
void swap2(int a,int b){
int tmp;
tmp = a;
a = b;
b = tmp;
}
void swap3(int a,int b){
a=a+b;
b=a-b;
a=a-b;
}
int main(){
int a = 3,b = 4;
clock_t start,stop;
double result;
start = clock();
for(int i = 0;i < 10000000;i ++)
swap1(a,b);
stop = clock();
result=(double)(stop-start)/CLOCKS_PER_SEC;
printf("异或交换时间:%lf\n",result);
start = clock();
for(int i = 0;i < 10000000;i ++)
swap2(a,b);
stop = clock();
result=(double)(stop-start)/CLOCKS_PER_SEC;
printf("中间变量交换时间:%lf\n",result);
start = clock();
for(int i = 0;i < 10000000;i ++)
swap3(a,b);
stop = clock();
result=(double)(stop-start)/CLOCKS_PER_SEC;
printf("加减法交换时间:%lf\n",result);
system("pause");
return 0;
}
将操作次数提升一个数量级后,可以发现利用异或运算来交换两个变量的值的方法效率最低。