struct Edge
{
int sursa, destinatie, cost;
};
struct Graf
{
int E, M;
struct Edge edge[MAX_EDGES];
};
int ComparaCost(const void* x, const void* y)
{
struct Edge* a_edge = (struct Edge*) x;
struct Edge* b_edge = (struct Edge*) y;
return a_edge -> cost > b_edge -> cost;
}
qsort(g -> edge, g -> E, sizeof(g->edge[0]), ComparaCost);
我不知道为什么函数不按成本(权重)以递增的顺序对边缘进行排序。我的意思是,它稍微改变了图中边缘的顺序,但没有正确的方式。
您没有通过qsort
比较器功能重现正确的值,>
return a_edge -> cost > b_edge -> cost;
它绝不会根据需要返回负值。请尝试
if(a_edge->cost > b_edge->cost) return 1; if(a_edge->cost < b_edge->cost) return -1; return 0;
有时编码员使用
return a_edge->cost - b_edge->cost;
但是会溢出算术
((请注意,请不要在->
周围留空格,以提高可读性。
至少,排序函数必须返回3种值:当x < y,
x == y
,x > y
时为负,零,正。