-1

I have this peace of code in wiki page about sorting. I suppose it has to swap to array elements, but can somebody explain it properly

   array[i] ^= array[i-1];
   array[i-1] ^= array[i];
   array[i] ^= array[i-1];

wiki page https://ru.wikipedia.org/wiki/%D0%A1%D0%BE%D1%80%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%BA%D0%B0_%D0%BF%D0%B5%D1%80%D0%B5%D0%BC%D0%B5%D1%88%D0%B8%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5%D0%BC

Alex Zveruk
  • 73
  • 2
  • 6

1 Answers1

3

That is a way of swapping array[i] and array[i-1].

^= does a bitwise XOR between the two arguments and assigns it to the left one.
To see how that causes a swap lets consider just a pair of bits : A and B which contain values x and y respectively .

  • Before starting we have :
    A = x
    B = y
  • First instruction A^=B means A = ( A XOR B ) So we end up with :
    A = x XOR y
    B = y
  • Second instruction B^=A means B = ( B XOR A) So we end up with :
    A = x XOR y
    B = y XOR ( x XOR y )
  • Third instruction A^=B means A = ( A XOR B) So we end up with :
    A = (x XOR y ) XOR ( y XOR ( x XOR y ) )
    B = y XOR ( x XOR y )
  • Making use of the associativity and conmutativity of XOR we can reorder the previous operations as :
    A = (x XOR x) XOR (y XOR y) XOR y
    B = (y XOR y) XOR x
  • Making use of the property that a bit XOR itself is always 0 :
    A = 0 XOR 0 XOR y
    B = 0 XOR x
  • Making use the property that 0 XOR a bit is always the same bit :
    A = y
    B = x

As you can see A and B have been swapped.

Anonymous Coward
  • 3,140
  • 22
  • 39