C#列表.排序不';t排序

本文关键字:排序 列表 | 更新日期: 2023-09-27 18:24:26

我有一个List<T>要排序,所以我使用了List<T>.Sort(Comparison<T>)。我的代码没有按预期工作,经过一些调试,我发现虽然其中包含的项目的顺序确实发生了变化,但它并没有排序
代码在这里:

System.Comparison<Intersection> comp=(Intersection one, Intersection other)=>{//Sort sorts from lowest to highest
    if(one.index>other.index){
        return 1;
    }
    else if(one.index<other.index){
        return -1;
    }
    else if((one.point-one.node.position).sqrMagnitude>(other.point-other.node.position).sqrMagnitude){
        return 1;
    }
    else{
        return -1;
    }
};
intersections.Sort(comp);

问题是,在排序之后,可以按顺序找到项目,使得第三个项目具有索引7,而第四个项目具有6。我认为比较lambda可能有问题,但我添加了一个代码,该代码使用相同的函数来比较顺序项,但它表现正确,有时返回1,所以问题显然在其他地方
之后的比较:

for(int he=1; he<intersections.Count; he++){
    Debug.Log(comp(intersections[he-1], intersections[he]));
}

是我遗漏了什么,还是我的List<T>.Sort实现有问题,我应该制定自己的排序方法?

结构如下:

class Intersection{
    public PolyNode node;
    public int index;
    public Polygon poly;
    public Intersection sister;
    public bool is_out;
    public sbyte wallnum;
    public Vector2 point;
    public int list_index;
}

C#列表.排序不';t排序

要扩展500内部服务器错误(正确)的答案,Quicksort需要一个性能良好的比较函数。您需要提供以下比较:

  • 是自反的:项必须与自身比较相等
  • 在不等式中是反对称的:如果A大于B,则B必须也小于A
  • 在等式中是对称的:如果A等于B,则B必须也等于A
  • 是可传递的:如果A等于B,B等于C,则A必须等于C。如果A大于B,B大于C,则A+strong>必须大于C。依此类推

简而言之,必须提供总订购关系。您的比较算法违反了其中的许多要求。任何时候你不能提供一个完整的订购关系,坏的事情都可能发生。该算法可能崩溃,可能进入无限循环,也可能返回未排序的列表。

要进行更长的讨论,请参阅我的四部分系列文章,这些文章讲述了我看到错误比较算法的常见方法:

http://ericlippert.com/2011/01/20/bad-comparisons-part-one/

正如其他人所指出的,您的比较函数从不返回零(相等)的结果,但List.Sort依赖于比较函数在将项与自身进行比较时返回相等。