排序数组的最快方法c#

时间:2016-10-27 06:56:23

标签: c# arrays performance sorting quicksort

嗨,这是我的问题我有一个点P(x,y)的数组,我需要从最远到最近的这些点排序,相对于多边形的重心,这就是我所做的(我知道)这是一个糟糕的解决方案)我怎样才能做得更好,更快速的解决方案呢?

List<C2DPoint> OrderedGripperPoints = new List<C2DPoint> { };

while(myGripperPoints.Count!=0) 
{
    double dist=-1;
    int index=-1;
    for(int k=0;k<myGripperPoints.Count;k++)
    {
        if(myGripperPoints[k].Distance(WorkScrap.GetCentroid())>=dist)
        {
            index = k;
            dist = myGripperPoints[k].Distance(WorkScrap.GetCentroid());
        }
    }

    OrderedGripperPoints.Add(myGripperPoints[index]);
    myGripperPoints.RemoveAt(index);
}

感谢您的回答......

2 个答案:

答案 0 :(得分:4)

使用Linq订购积分。

using System.Linq;

var sortedList = myGripperPoints.OrderBy(p => p.Distance(WorkScrap.GetCentroid())).ToList();

答案 1 :(得分:1)

请考虑以下代码:

Point Class(假定的类定义)

class Point
{
    public int X { get; set;}

    public int Y { get; set;}   
}

Point EqualityComparer

class PointEqualityComparer : IEqualityComparer<Point>
{
    public bool Equals(Point p1, Point p2) { return p1.X == p2.X && p1.Y == p2.Y; }

    public int GetHashCode(Point p) { return p.X.GetHashCode() *31 + p.Y.GetHashCode()*23; }
}

创建一个以点为键,距离为值的字典(假设为整数):

Dictionary<Point,int> pointDictionary = 
new Dictionary<Point, int>(new PointEqualityComparer());

按如下方式添加积分:

Point p = new Point {X = <value>, Y = <value>};
pointDictionary.Add(p,p.Distance(WorkScrap.GetCentroid()));

按距离排序如下:

pointDictionary.OrderByDescending(x => x.Value).ToList();
  1. 按预期的降序距离完成订购
  2. 结果为List<KeyValuePair<Point,int>>,其中元素为降序