我正在尝试按变量 a 对结构节点进行排序,但结果证明是错误的。
我的结果:
{5, 4}, {6, 2}, {7, 3}, {4, 1}, {3, 7}, {1, 3}, {0, 0},
我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int x;
int y;
} n;
int num = 7;
int compare(const void *ele1, const void *ele2) {
n *px, *py;
px = (n *) ele1;
py = (n *) ele2;
return px->x < py->x;
}
int main() {
n node[7] = {
{4, 1},
{6, 2},
{1, 3},
{5, 4},
{7, 3},
{3, 7}
};
int i;
qsort(node, num, sizeof (node[0]), compare);
for (i = 0; i < num; i++)
printf("{%d, %d}, ", node[i].x, node[i].y);
return 0;
}
如果我只对六对元素进行排序,那么结果是:
{7, 3}, {6, 2}, {5, 4}, {4, 1}, {1, 3}, {0, 0},
这是正确的,但是当我尝试使用七个时,它显示了上面的结果。有谁知道为什么会这样?谢谢!