I am using QuickSort in C.
Here is my swap procedure:
void swap(int *x, int *y) { *x += (*y); *y = (*x) - (*y); *x = (*x) - (*y); }
And here is my section procedure:
int partition(int a[], int sx, int dx) { int indice_pivot = (rand()%(dx-sx+1))+sx; int i = sx-1, j; swap(&a[indice_pivot],&a[dx]); for(j=sx;j<dx;j++) { if(a[j] <= a[dx]) { i++; swap(&a[j],&a[i]); } } i++; swap(&a[i],&a[dx]); return i; }
The problem is that when replacing two variables they magically (?) Become 0. I did some debugging and everything seems to work fine in the swap procedure. But the array contains zeros at the end of some sections (not all of them). It is strange that if I replaced the swap procedure with
void swap(int *x, int *y) { int temp = *y; *y = *x; *x = temp; }
Everything works perfectly. Why?
c quicksort swap
Davide R.
source share