我使用xor-swap的插入排序不起作用,但没有xor-swap它的工作正常。 如何修复xor-swap插入排序算法?
不带xor-swap的插入排序 -
//sorts the given array in " increasing order "
private static void insertionSort(char[] array) {
// save the length of array
final int LENGTH = array.length ;
//loop through selecting second character as first element is already sorted
for(int i = 1 ; i < LENGTH ; ++i )
{
char current = array[i];
//place the array[i] in "order" with elements placed towards left of itself
for( int j = i - 1 ; (j >=0 && array[j+1] < array[j]) ; --j )
{
array[j+1] = array[j] ;
array[j] = current ;
}
}
}
使用xor-swap -
//sorts the given array in " increasing order "
private static void insertionSort(char[] array) {
// save the length of array
final int LENGTH = array.length ;
//loop through selecting second character as first element is already sorted
for(int i = 1 ; i < LENGTH ; ++i )
{
//char current = array[i];
//place the array[i] in "order" with elements placed towards left of itself
for( int j = i - 1 ; (j >=0 && array[j+1] < array[j]) ; --j )
{
array[j+1] ^= array[j] ^= array[j+1] ^= array[j] ;
//array[j] = current ;
}
}
}
谢谢
答案 0 :(得分:2)
执行顺序与^=
运算符是正确关联的,因此您编写的代码等同于:
a ^= (b ^= (a ^= b));
^ =运算符只是a = a ^ b的缩写,所以如果你完全扩展它,你得到:
a = a ^ (b = b ^ (a = a ^ b));
现在请记住,a
的值将在表达式的评估开始时进行,而不是在执行时。想象一下a
和b
取值5
和10
。你有效地计算:
a = 5 ^ (b = 10 ^ (a = 5 ^ 10));
您实际上需要首先5
为15
才能使交换正常工作。
因此,正如Alan Stokes指出的那样,你需要将表达式分成三个(或者只是两个)语句,以告诉编译器每个语句的结果应该用于下一个计算阶段。 / p>
a ^= b;
b ^= a;
a ^= b;