C库中的快速排序 qsort的第二个参数
现在我想按x对一组点进行排序。下面是我的代码:C库中的快速排序 qsort的第二个参数,c,quicksort,C,Quicksort,现在我想按x对一组点进行排序。下面是我的代码: 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;
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;
}
typedef结构{
int x;
int-y;
}点;
int cmpfunc(常数无效*a,常数无效*b){
点*点1=(点*)(a);
点*点2=(点*)(b);
如果(点1->x<点2->x){
返回-1;
}
返回0;
}
int main(){
点*点=(点*)malloc(尺寸(点)*3);
点[0].x=1;
点[0],y=2;
点[1],x=0;
点[1],y=4;
点[2],x=4;
点[2],y=3;
qsort(点2,(sizeof(点[0])),cmpfunc;
int i=0;
虽然(i要在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;
}
静态无效cmpfunc(常量无效*a,常量无效*b)
{
常数点*pa=a,*pb=b;
返回pa->xx-1:pa->x>pb->x;
}
它必须返回小于、等于或大于零的值
哦,你真的不应该无缘无故地那样“删除常量”,当然你也不需要像我们这里这样从void*
到struct
的指针进行强制转换。保持简单,学习这些东西,这样你就不必“为了更好的度量而进行强制转换”.您的比较函数已损坏,它不会返回大于零的值。谢谢much@unwindAnother可能的问题:您正在对3中的2个元素进行排序,为什么?