在QuickSort中交换两个变量时会发生奇怪的事情
发布时间:2020-12-16 04:54:58 所属栏目:百科 来源:网络整理
导读:我正在C中实现QuickSort. 这是我的交换程序: void swap(int *x,int *y){ *x += (*y); *y = (*x) - (*y); *x = (*x) - (*y);} 这是我的分区程序: int partition(int a[],int sx,int dx){ int indice_pivot = (rand()%(dx-sx+1))+sx; int i = sx-1,j; swap(a
我正在C中实现QuickSort.
这是我的交换程序: void swap(int *x,int *y) { *x += (*y); *y = (*x) - (*y); *x = (*x) - (*y); } 这是我的分区程序: 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; } 问题是,当交换两个变量时,它们神奇地(?)变为0.我做了一些调试,一切似乎在交换过程中工作正常.但是数组在某些分区的末尾包含零(并非所有分区). void swap(int *x,int *y) { int temp = *y; *y = *x; *x = temp; } 一切正常.为什么? 解决方法
如果两个指针指向同一元素,则交换功能将不起作用.如果他们做第二步* y =(* x) – (* y);将元素设置为0,因为它等于* x =(* x) – (* x);
带有temp变量的第二个交换函数会保留这些值. 一眼就看起来像是交换(& a [indice_pivot],& a [dx]);可能会击中相同的元素.您可以使用assert(indice_pivot!= dx)来确定(或者当然在交换函数中放置一个). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |