XOR Swap algorithm weird error?

Jun 11, 2017 at 9:57am
I was implementing a quick sort on some array but I encountered this weird error:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
int part(int a[], int low, int high){
int piv = a[high];
int index = low;
for(int i = low; i < high; i++){
    if(a[i] <= piv){
        a[i] ^= a[index];
        a[index] ^= a[i];
        a[i] ^= a[index];
       //tried a[i]^=a[index]^=a[i]^=a[index] and same result.
        index++;
    }
}
swap(a[index], a[high]);
return index;
}
void quick_sort(int a[], int low, int high){
if(low >= high) return;

int piv = part(a, low, high);
quick_sort(a, low, piv-1);
quick_sort(a, piv+1, high);
}

int main()
{

    int a[9] = {31, 41, 59, 206, 200, 25111, 26, 41, 58};
    quick_sort(a,0,8);


    for(auto x: a) cout << x << " ";


    return 0;
}


And this outputs:
0 0 0 41 58 59 200 0 25111


Meanwhile if I switch it to a normal swap:
1
2
3
4
if(a[i] <= piv){
        swap(a[i],a[index]);
        index++;
    }


outputs:
26 31 41 41 58 59 200 206 25111


Why is that happening?
Jun 11, 2017 at 12:28pm
XOR-swap does not work if you are swapping an array element with itself.
Jun 11, 2017 at 2:50pm
Thanks!
Jun 11, 2017 at 8:01pm
xor swap is also slower usually. The cpu has to do the xor AND the same number of real data copies. Its a cute algorithm for exams and interviews, with little practical value.

The fastest swap usually needs hands on assembler, its hard to get the computer to do mov ax, x mov bx, y mov y, ax, mov x, bx or the stack push push pop pop one (I forget which of those 2 wins). Hopefully std swap does the better of those 2.

Last edited on Jun 11, 2017 at 8:03pm
Topic archived. No new replies allowed.