使用java调试xor-swap for Insertion Sort

时间:2014-07-26 12:28:51

标签: java sorting

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




    }

谢谢

1 个答案:

答案 0 :(得分:2)

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

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指出的那样,你需要将表达式分成三个(或者只是两个)语句,以告诉编译器每个语句的结果应该用于下一个计算阶段。 / p>

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