Home > Software design >  what is wrong with this swap function
what is wrong with this swap function

Time:10-03

I am looking at quick sort program where swap function was not defined, and then I tried to define it myself.

#include <stdio.h>
#include <stdint.h>

void swap(int *x, int *y)
{
         int tmp;
#if 1
        *x = *x ^ *y;
        *y = *y ^ *x;
        *x = *x ^ *y;
#endif

#if 0
        tmp = *x;
        *x  = *y;
        *y  = tmp; 
#endif

}

int partiotion(int a[], int low, int high)
{
        int i=low;
        int pivot_key = a[low];
        int j=high;

    do 
    {
        do { i  ;} while (a[i] <= pivot_key);
        do { j--;} while (a[j] > pivot_key);

        if (i<j) swap(&a[i], &a[j]);
    } while (i<j);

    swap(&a[low], &a[j]);
    return j; 
}

void quick(int a[], int low, int high)
{
    int j;  

    if (low<high)
    {
        j = partiotion(a, low, high);
        quick(a, low, j);
        quick(a, j 1, high);
    }
}

int main()
{
    int a[] = {1,3,9,8,7, INT32_MAX}, i;

    quick(a, 0, 5);
    
    for(i=0; i < 5; i  )
        printf("%d\n", a[i]);
}

But output of program comes out to be:

./a.out

0

0

0

0

9

if I use tmp variable (for swap) it just works fine, but what is wrong with pointer version of swap ?

CodePudding user response:

The problem arises when you incidentally call swap(&a[i], &a[i]) (with the same index). Both pointers refer to the same array item. After the first XOR the item becomes 0, regardless of what it was before.

  • Related