您的位置:首页 > 其它

[转]多边形点集排序--针对凸多边形,按逆时针方向进行排序

2013-11-13 10:08 323 查看
原文地址:/article/4983856.html

原文是C++下的,稍微的改了为C#的,呵呵

主要方法:

public static void ClockwiseSortPoints(List<Point3D> vPoints)
{
//计算重心
Point3D center = new Point3D();
double X = 0, Y = 0;
for (int i = 0; i < vPoints.Count; i++) {
X += vPoints[i].X;
Y += vPoints[i].Y;
}
center.X = (int)X / vPoints.Count;
center.Y = (int)Y / vPoints.Count;

//冒泡排序
for (int i = 0; i < vPoints.Count - 1; i++) {
for (int j = 0; j < vPoints.Count - i - 1; j++) {
if (PointCmp(vPoints[j], vPoints[j + 1], center)) {
Point3D tmp = vPoints[j];
vPoints[j] = vPoints[j + 1];
vPoints[j + 1] = tmp;
}
}
}
}


辅助方法:

//若点a大于点b,即点a在点b顺时针方向,返回true,否则返回false
static bool PointCmp(Point3D a, Point3D b, Point3D center)
{
if (a.X >= 0 && b.X < 0)
return true;
if (a.X == 0 && b.X == 0)
return a.Y > b.Y;
//向量OA和向量OB的叉积
int det = Convert.ToInt32((a.X - center.X) * (b.Y - center.Y) - (b.X - center.X) * (a.Y - center.Y));
if (det < 0)
return true;
if (det > 0)
return false;
//向量OA和向量OB共线,以距离判断大小
double d1 = (a.X - center.X) * (a.X - center.X) + (a.Y - center.Y) * (a.Y - center.Y);
double d2 = (b.X - center.X) * (b.X - center.Y) + (b.Y - center.Y) * (b.Y - center.Y);
return d1 > d2;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: