两数交换算法
public class Demo { private static long n = 1000000000; /** * @param args */ public static void main(String[] args) { int a=10,b=20; long begin = System.currentTimeMillis(); swap1(a, b); long end = System.currentTimeMillis(); System.out.println(end - begin); begin = System.currentTimeMillis(); swap2(a, b); end = System.currentTimeMillis(); System.out.println(end - begin); begin = System.currentTimeMillis(); swap3(a, b); end = System.currentTimeMillis(); System.out.println(end - begin); } /** * * @param a * @param b */ public static void swap1(int a, int b){ for(long i = 0; i < n; i++){ a = a ^ b; b = a ^ b; a = a ^ b; } } public static void swap2(int a, int b){ int temp; for(long i = 0; i < n; i++){ temp = a; a = b; b = temp; } } /** * 两个数过大,会溢出 * @param a * @param b */ public static void swap3(int a, int b){ for(long i = 0; i < n; i++){ a = a + b; b = a - b; a = a - b; } } }