0

I can not understand what does it mean "^=". I was readind wiki abou CocktailSort and meet this signs it the code. Does it s something like swap?

public class CocktailSort
{

public static void main(String[] args)
{
    int[] array = {3, 1, 5, 8, 1, 0, 6, 4, 6, 7};
    int left = 0; // левая граница
    int right = array.length - 1; // правая граница

    do
    {
        //Сдвигаем к концу массива "тяжелые элементы"
        for (int i = left; i < right; i++)
        {
            if(array[i] > array[i+1])
            {
                array[i] ^= array[i+1];
                array[i+1] ^= array[i];
                array[i] ^= array[i+1];
            }
        }
        right--; // уменьшаем правую границу
        //Сдвигаем к началу массива "легкие элементы"
        for (int i = right; i > left ; i--)
        {
            if(array[i] < array[i-1])
            {
                array[i] ^= array[i-1];
                array[i-1] ^= array[i];
                array[i] ^= array[i-1];
            }
        }
        left++; // увеличиваем левую границу
    } while (left <= right);

    for (int i : array) System.out.print(i + " "); // вывод массива на экран
}
}

P s it on russian wiki

Alex Zveruk
  • 73
  • 2
  • 6
  • `array[i] ^= array[i+1]` is equal to `array[i] = array[i] ^ array[i+1]`. The ^ operator is the bitwise exclusive OR (XOR) operator. – marstran Aug 08 '15 at 16:21
  • Like marstran said the 3 statements exchange the values of array[i] and [i+1]. Its a convoluted way of doing this that is an optimization in some assembler languages and possibly in C (depending on platform). In Java its just convoluted, a temporary int variable would do the same and be much easier to read. And faster too, in case of java. – Durandal Aug 08 '15 at 16:35

0 Answers0