C 库中的快速排序

QuickSort in C library

qsort的第二个参数

现在我想按 x.Following 对一组点进行排序是我的代码:

typedef struct {
    int x;
    int y;
} point;

int cmpfunc( const void * a, const void * b){
    point *point1 = (point *)(a);
    point *point2 = (point *)(b);

    if(point1->x < point2->x){
        return -1;
    }
    return 0;
}

int main(){

    point *points = (point *)malloc(sizeof(point)*3);
    points[0].x = 1;
    points[0].y = 2;

    points[1].x = 0;
    points[1].y = 4;

    points[2].x = 4;
    points[2].y = 3;

    qsort(points,2,(sizeof(points[0])),cmpfunc);

    int i=0;
    while (i<3){
        printf("x=%d",points[i].x);
        printf("y=%d\n",points[i].y);
        i++;
    }
    return 0;
}

请注意qsort(points,2,(sizeof(points[0])),cmpfunc);

当我传递第二个参数值 2 而不是 3 时,结果是正确的。我的代码有什么问题?

要在 x 轴上排序,您需要如下内容:

static void cmpfunc(const void *a, const void *b)
{
  const point *pa = a, *pb = b;
  return pa->x < pb->x ? -1 : pa->x > pb->x;
}

它必须 return 小于、等于或大于零。 See the manual page 更多。

哦,你真的不应该 "drop const" 那样,无缘无故,当然你永远不需要像我们一样从 void * 转换为指向 struct 的指针有这里。保持简单,学习这些东西,这样您就不需要 "throw in a cast for good measure".