java交换两个数的常见方法及效率测试

来源:互联网 发布:古代战争 知乎 编辑:程序博客网 时间:2024/05/22 06:28

原文地址——http://blog.csdn.net/qq525099302/article/details/47294443

论两个数的交换的重要性

讨论交换两个数的方法对某些人来说无聊,但某些人很乐意探究,甚至某些面试官喜欢用这个做文章。刚出来找工作笔试的时候我也碰到与之相关的问题。

常见的两个数交换的方法

  • 边赋值边运算
  • 加减减交换
  • 用中间变量交换
  • 异或交换

下面是代码

public class Test {    public static void main(String[] args) {        long start,end;         int a = 100000, b = 200000, t;        start = System.currentTimeMillis();        for (int i = 0; i <= 1000000000; i++) {// 边赋值边运算——462            a = b + (b = a) * 0;        }        end = System.currentTimeMillis();        System.out.println(end - start);        start = System.currentTimeMillis();        for (int i = 0; i <= 1000000000; i++) {// 加减减交换——898            a += b;            b = a - b;            a -= b;        }        end = System.currentTimeMillis();        System.out.println(end - start);        start = System.currentTimeMillis();        for (int i = 0; i <= 1000000000; i++) {// 用中间变量交换——449            t = a;            a = b;            b = t;        }        end = System.currentTimeMillis();        System.out.println(end - start);        start = System.currentTimeMillis();        for (int i = 0; i <= 1000000000; i++) {// 异或交换——896            a ^= b;            b ^= a;            a ^= b;        }        end = System.currentTimeMillis();        System.out.println(end - start);    }}

说明

注释后面的数字是我的电脑运行10亿次交换所用的时间(毫秒)

总结

如果没有强迫症或者硬性要求,用中间变量交换是最好的方法。
如果要走非主流边赋值边运算是最有效率的。
加减减和异或虽然看起来挺酷的,但是运算多,慢是应该的。
统计

0 0