Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 在快速排序中交换两个变量时会发生奇怪的事情_C_Quicksort_Swap - Fatal编程技术网

C 在快速排序中交换两个变量时会发生奇怪的事情

C 在快速排序中交换两个变量时会发生奇怪的事情,c,quicksort,swap,C,Quicksort,Swap,我正在用C实现快速排序 以下是我的交换过程: 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_pivo

我正在用C实现快速排序

以下是我的交换过程:

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;
}
下面是我的分区过程:

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;
}
一切正常。为什么?

交换(…)
  • 有符号整数溢出未定义,如果
    *x
    *y
    足够大,则可能会发生此溢出
  • 绝对没有人能轻易判断实现
    swap()
    的代码是否正确
分区(…)
  • 如果
    i==j
    ,swap()函数将无法正常工作。这是因为在
    swap()

如果两个指针指向同一个元素,则交换函数将不起作用。如果他们执行第二步
*y=(*x)-(*y)
将元素设置为0,因为它相当于
*x=(*x)-(*x)

带有temp变量的第二个swap函数保留这些值


乍一看,它看起来像
swap(&a[indice_pivot]、&a[dx])可能命中同一个元素。您可以使用断言(indice_pivot!=dx)
来确定(当然也可以将其放入交换函数中)。

@David Ok。那是不是第一次交换击中了同一个元素?是的。再次感谢。我认为这是一堂宝贵的人生课。为了在临时变量上保存4个字节,您太过努力了。这表明最好释放4个字节,并有可维护和工作的代码。