C语言中使用qsort函数排序平面点结构体的技术求助
我来帮你完成这个用qsort对笛卡尔平面点排序的程序,顺便修正你代码片段里的小问题~
使用qsort对笛卡尔平面点排序的完整实现
首先,你代码里的typedef有个小错误:应该是typedef struct x_y coordinates;,而不是typedef coordinate...。下面是完整的可运行代码,完全匹配你的排序需求:
#include <stdio.h> #include <stdlib.h> // 定义笛卡尔点的结构体 typedef struct x_y { int x; int y; } coordinates; // qsort所需的比较函数,核心排序逻辑 int comparePoints(const void *a, const void *b) { // 将void指针转换为结构体指针 const coordinates *pointA = (const coordinates *)a; const coordinates *pointB = (const coordinates *)b; // 优先按x轴升序排列 if (pointA->x != pointB->x) { return pointA->x - pointB->x; } // x值相同时,按y轴降序排列 else { return pointB->y - pointA->y; } } int main() { int n; // 读取点的数量 scanf("%d", &n); // 动态分配结构体数组内存(也可以用静态数组,动态方式更灵活) coordinates *points = (coordinates *)malloc(n * sizeof(coordinates)); if (points == NULL) { printf("内存分配失败\n"); return 1; } // 读取每个点的x、y坐标 for (int i = 0; i < n; i++) { scanf("%d %d", &points[i].x, &points[i].y); } // 调用qsort执行排序 qsort(points, n, sizeof(coordinates), comparePoints); // 输出排序后的结果 for (int i = 0; i < n; i++) { printf("%d %d ", points[i].x, points[i].y); } printf("\n"); // 释放动态分配的内存 free(points); return 0; }
关键细节说明
- 比较函数
comparePoints:这是qsort的核心,必须遵循它的函数签名规则:- 当
pointA->x < pointB->x时,返回负数,qsort会把pointA排在前面,实现x轴升序; - 当x值相等时,返回
pointB->y - pointA->y:如果pointB->y更小,返回负数,qsort会把pointA(y值更大的点)排在前面,实现y轴降序。
- 当
- qsort参数:
qsort(数组首地址, 元素个数, 单个元素大小, 比较函数指针),这里我们传入动态分配的points数组、点的数量n、结构体大小sizeof(coordinates),以及自定义的比较函数。
示例验证
输入:
5 2 5 12 2 2 7 3 4 2 2
输出:
2 7 2 5 2 2 3 4 12 2
完全符合你的需求。
内容的提问来源于stack exchange,提问作者Maggiorana




