qsort() 图结构数组

qsort() an array of graph structures

struct Edge
{
    int src, dest, weight;
}; typedef struct Edge Edge;

struct Graph
{
    int V, E;
    Edge* edge;
}; typedef struct Graph Graph;

我有一个这样的图形结构。我正在尝试使用 qsort 按权重的递增顺序对所有边进行排序。 主要:

Graph* graph = (Graph*)malloc(sizeof(Graph));
qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp);

Mycomp 函数:

    int myComp(const void* a, const void* b)
{
    Edge* a1 = (Edge*)a;
    Edge* b1 = (Edge*)b;
    return a1->weight > b1->weight;
}

毕竟,我尝试打印qsort前后的每条边,顺序已经改变但不是正确的顺序。任何人都可以帮助解决这些问题吗?我的代码哪一部分有问题?

return a1->weight > b1->weight;

应该是

return a1->weight - b1->weight;

来自手册:

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

@n.m 的答案无需添加任何内容。

但是,如果您编写

,您可以稍微压缩您的声明
typedef struct Edge
{
    int src, dest, weight;
} Edge;

甚至

typedef struct
{
    int src, dest, weight;
} Edge;

如果您打算仅使用类型定义的名称 Edge,并且不需要基本类型的显式名称 struct Edge