[英]Fastest way to sort an Array c#
Hi this is my problem I have an array of points P(x,y) and I need to sort these points from the furthest to the closest, respect to the barycenter of a Polygon, this what I have done (I know this is a bad solution ) how can I do a better and aboveall faster solution? 嗨,这是我的问题,我有一个点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);
}
Thanks for your answers... 感谢您的回答...
Use Linq to order points. 使用Linq排序点。
using System.Linq;
var sortedList = myGripperPoints.OrderBy(p => p.Distance(WorkScrap.GetCentroid())).ToList();
Consider the following code: 考虑以下代码:
Point Class (assumed class definition) 点类(假设类定义)
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; }
}
Create a Dictionary with Point as Key and Distance as value (assuming integer): 创建一个字典,将Point作为键,将Distance作为值(假设为整数):
Dictionary<Point,int> pointDictionary =
new Dictionary<Point, int>(new PointEqualityComparer());
Add Points as follows: 添加点如下:
Point p = new Point {X = <value>, Y = <value>};
pointDictionary.Add(p,p.Distance(WorkScrap.GetCentroid()));
Order by Distance as follows: 按距离排序如下:
pointDictionary.OrderByDescending(x => x.Value).ToList();
List<KeyValuePair<Point,int>>
, where elements are in Descending order List<KeyValuePair<Point,int>>
,其中元素按降序排列
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.