两个数交换的四种常用方法:
1.中间变量交换
2.加减减法交换
3.赋值交换
4.异或交换
以下是Java代码:
public static void main(String []args){
long start, end;
int a = 10, b = 20;
long count = 1000000000L;
start = System.currentTimeMillis();
for(long i = 0; i < count; i++){
a = b + (b = a) * 0;
}
end = System.currentTimeMillis();
a = b + (b = a) * 0;
System.out.println("a=" + a +" " + "b=" + b);
System.out.println("赋值交换耗时:" + (end-start) + "ms");
a = 10; b = 20; //恢复原a、b值
start = System.currentTimeMillis();
for(long i = 0; i < count; i++){
a += b;
b = a - b;
a -= b;
}
end = System.currentTimeMillis();
a += b;
b = a - b;
a -= b;
System.out.println("a=" + a +" " + "b=" + b);
System.out.println("加减减交换耗时:" + (end-start) + "ms");
a = 10; b = 20; //恢复原a、b值
start = System.currentTimeMillis();
int t;
for(long i = 0; i < count; i++){
t = a;
a = b;
b = t;
}
end = System.currentTimeMillis();
t = a;
a = b;
b = t;
System.out.println("a=" + a +" " + "b=" + b);
System.out.println("中间变量交换耗时:" + (end-start) + "ms");
a = 10; b = 20; //恢复原a、b值
start = System.currentTimeMillis();
for(long i = 0; i < count; i++){
a ^= b;
b ^= a;
a ^= b;
}
end = System.currentTimeMillis();
a ^= b;
b ^= a;
a ^= b;
System.out.println("a=" + a +" " + "b=" + b);
System.out.println("异或交换耗时:" + (end-start) + "ms");
}
long start, end;
int a = 10, b = 20;
long count = 1000000000L;
start = System.currentTimeMillis();
for(long i = 0; i < count; i++){
a = b + (b = a) * 0;
}
end = System.currentTimeMillis();
a = b + (b = a) * 0;
System.out.println("a=" + a +" " + "b=" + b);
System.out.println("赋值交换耗时:" + (end-start) + "ms");
a = 10; b = 20; //恢复原a、b值
start = System.currentTimeMillis();
for(long i = 0; i < count; i++){
a += b;
b = a - b;
a -= b;
}
end = System.currentTimeMillis();
a += b;
b = a - b;
a -= b;
System.out.println("a=" + a +" " + "b=" + b);
System.out.println("加减减交换耗时:" + (end-start) + "ms");
a = 10; b = 20; //恢复原a、b值
start = System.currentTimeMillis();
int t;
for(long i = 0; i < count; i++){
t = a;
a = b;
b = t;
}
end = System.currentTimeMillis();
t = a;
a = b;
b = t;
System.out.println("a=" + a +" " + "b=" + b);
System.out.println("中间变量交换耗时:" + (end-start) + "ms");
a = 10; b = 20; //恢复原a、b值
start = System.currentTimeMillis();
for(long i = 0; i < count; i++){
a ^= b;
b ^= a;
a ^= b;
}
end = System.currentTimeMillis();
a ^= b;
b ^= a;
a ^= b;
System.out.println("a=" + a +" " + "b=" + b);
System.out.println("异或交换耗时:" + (end-start) + "ms");
}