gpt4 book ai didi

java - 使用java为插入排序调试xor-swap

转载 作者:行者123 更新时间:2023-11-29 05:20:29 29 4
gpt4 key购买 nike

我使用 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 ;
}
}



}

用异或交换--

//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 ;
}
}




}

谢谢

最佳答案

执行顺序与 ^= 运算符右关联,因此您编写的代码等同于:

a ^= (b ^= (a ^= b));

^= 运算符只是 a = a ^ b 的简写,所以如果你完全展开它,你会得到:

a = a ^ (b = b ^ (a = a ^ b));

现在请记住,a 的值将在表达式求值开始时获取,而不是在执行时获取。假设 ab 取值 510。您正在有效地计算:

a = 5 ^ (b = 10 ^ (a = 5 ^ 10));

您实际上需要第一个 515 才能使交换工作。

因此,正如 Alan Stokes 所指出的,您需要将表达式分成三个(或两个)语句,以便告诉编译器每个语句的结果应该用于下一阶段的计算。

a ^= b;
b ^= a;
a ^= b;

关于java - 使用java为插入排序调试xor-swap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24971035/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com