I did some tests using XOR and temporary: XOR is about two times slower.
Here the code:
public class Swap {
private static void swap1(int[] a) {
int half = a.length / 2;
Timer timer = new Timer();
for (int repeat = 201; repeat > 0; repeat--) {
for (int i = 0, j = a.length-1; i < half; i++,j--) {
a[i] ^= a[j];
a[j] ^= a[i];
a[i] ^= a[j];
}
}
Times times = timer.times();
System.out.println("swap1: " + times);
}
private static void swap2(int[] a) {
int half = a.length / 2;
Timer timer = new Timer();
for (int repeat = 201; repeat > 0; repeat--) {
for (int i = 0, j = a.length-1; i < half; i++,j--) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
Times times = timer.times();
System.out.println("swap2: " + times);
}
public static void main(String[]args){
int a[] = new int[102400];
for (int i = 0; i < a.length; i++) {
a[i] = i;
}
System.out.println(Arrays.toString(Arrays.copyOf(a, 10)) + "..." + Arrays.toString(Arrays.copyOfRange(a, a.length-10, a.length)));
swap1(a);
System.out.println(Arrays.toString(Arrays.copyOf(a, 10)) + "..." + Arrays.toString(Arrays.copyOfRange(a, a.length-10, a.length)));
swap2(a);
System.out.println(Arrays.toString(Arrays.copyOf(a, 10)) + "..." + Arrays.toString(Arrays.copyOfRange(a, a.length-10, a.length)));
swap1(a);
swap2(a);
}
}
And some typical results:
java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) Server VM (build 16.3-b01, mixed mode)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]...[102390, 102391, 102392, 102393, 102394, 102395, 102396, 102397, 102398, 102399]
swap1: elapsed=0,068 cpu=0,063 user=0,063 [seconds]
[102399, 102398, 102397, 102396, 102395, 102394, 102393, 102392, 102391, 102390]...[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
swap2: elapsed=0,035 cpu=0,031 user=0,031 [seconds]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]...[102390, 102391, 102392, 102393, 102394, 102395, 102396, 102397, 102398, 102399]
swap1: elapsed=0,063 cpu=0,063 user=0,063 [seconds]
swap2: elapsed=0,023 cpu=0,031 user=0,031 [seconds]
(each called two times to eliminate some start-up problems)