C中的qsort()函数不适用于我的图

问题描述 投票:-1回答:2

enter image description here

 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);

我不知道为什么函数不按成本(权重)以递增的顺序对边缘进行排序。我的意思是,它稍微改变了图中边缘的顺序,但没有正确的方式。

c arrays sorting qsort
2个回答
0
投票

您没有通过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;

但是会溢出算术

((请注意,请不要在->周围留空格,以提高可读性。


0
投票

至少,排序函数必须返回3种值:当x < y, x == yx > y时为负,零,正。

© www.soinside.com 2019 - 2024. All rights reserved.