c - qsort() 图结构数组

标签 c qsort

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.

关于c - qsort() 图结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37247751/

相关文章:

c - 在c中使用TCP的服务器-客户端

c - 使用 qsort 对结构数组进行排序

c - 让 C 在我的扬声器上播放不同的频率

c - 如何在C中将IP4和IP6地址转换为长值?

c - 为什么我们在 getopt() 函数中使用 argc 作为参数?

c++ - 查找 C 风格转换的工具

c - 将函数的输出按从高到低的顺序显示

c - 使用 C 中的 openmp,如何并行化包含用于 qsort 的嵌套比较函数的 for 循环?

c - 这段代码在 C qsort 中的含义是什么?

转换函数指针