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

时间:2016-02-18 08:54:15

标签: c# unity3d

我试图对列表进行排序,但它没有对列表进行排序。

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.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,47.01,40.01,40.51,40.51,39.51,40.01,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,40.51,39.01,2.01,2.01,

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

为什么结果没有排序?

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

1 个答案:

答案 0 :(得分:1)

你的eps常数可能有问题。 以下比较功能应该有效。

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