使用 IComparer 对列表进行排序返回错误的结果

本文关键字:返回 错误 结果 排序 IComparer 列表 使用 | 更新日期: 2023-09-27 18:35:20

我正在尝试对列表进行排序,但它没有正确排序列表。

internal class GraphUtils{
    internal static List<Edge_t> kruskal2(List<Edge_t> e)
    {
       e.Sort(new KruskalComparer());
       printEdgeArray(e,e.Count);
       // Do stuff
    }
    static void printEdgeArray(List<Edge_t> e, int cnt)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < cnt; i++)
        {
            sb.Append(e[i].weight).Append(",");
        }
        ConsoleLog.Log(sb.ToString());
    }
}
internal class KruskalComparer : IComparer<Edge_t>
{
    public int Compare(Edge_t a, Edge_t b)
    {
        if (a.weight+TerrConstants.Eps > b.weight) return -1;
        if (a.weight < b.weight+TerrConstants.Eps) return 1;
        return 0;
    }
} 
class Edge_t
{
    internal Vertex_t V1;
    internal Vertex_t V2;
    internal float weight;
}

调用kruskal2时,排序后的数组将打印在控制台上。但结果是错误的。它不是按重量排序的 Edge_t .

75.01,78.01,76.51,75.51,75.51,75.01,75.01,75.01,74.51,73.01,71.01,71.01,71.01,71.01,71.01,72.51,71.01,71.01,71.01,71.01.71.01.51,71.51,71.01,79.01,63.01,63.01,59.01,47.01,59.51,47.01,59.01,42.01,47.01,42.01,47.01,47.01,47.01,47.01,40.01,40.51,40.51,39.01,39.01,24.51,38.51,

38.51,38.01,37.51

,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.51,24.01,24.51,2.01,2.01,2.01,24.01,24.51,2.01,2.01,2.01,24.51,2.01,24.51,2.0

我使用的是Unity3d,平台是单声道2.5.6。

为什么结果没有排序?

编辑:TerrConstants.Eps 是 1e-6f,它被添加到数字中以产生一些相等的余量。因此,如果差值小于TerrConstants.Eps*2则两个权重被视为相等。

使用 IComparer 对列表进行排序返回错误的结果

可能是你的 eps 常量有问题。以下比较函数应该可以工作。

if (Math.Abs(b.weight - a.weight) <= eps)
     return 0;
return b.weight.CompareTo(a.weight);