gpt4 book ai didi

c - qsort() 图结构数组

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:40 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com