[转]多边形点集排序--针对凸多边形,按逆时针方向进行排序
原文地址:http://www.cnblogs.com/dwdxdy/p/3230156.html
原文是C++下的,稍微的改了为C#的,呵呵
主要方法:
1 public static void ClockwiseSortPoints(List<Point3D> vPoints) 2 { 3 //计算重心 4 Point3D center = new Point3D(); 5 double X = 0, Y = 0; 6 for (int i = 0; i < vPoints.Count; i++) { 7 X += vPoints[i].X; 8 Y += vPoints[i].Y; 9 } 10 center.X = (int)X / vPoints.Count; 11 center.Y = (int)Y / vPoints.Count; 12 13 //冒泡排序 14 for (int i = 0; i < vPoints.Count - 1; i++) { 15 for (int j = 0; j < vPoints.Count - i - 1; j++) { 16 if (PointCmp(vPoints[j], vPoints[j + 1], center)) { 17 Point3D tmp = vPoints[j]; 18 vPoints[j] = vPoints[j + 1]; 19 vPoints[j + 1] = tmp; 20 } 21 } 22 } 23 }
辅助方法:
1 //若点a大于点b,即点a在点b顺时针方向,返回true,否则返回false 2 static bool PointCmp(Point3D a, Point3D b, Point3D center) 3 { 4 if (a.X >= 0 && b.X < 0) 5 return true; 6 if (a.X == 0 && b.X == 0) 7 return a.Y > b.Y; 8 //向量OA和向量OB的叉积 9 int det = Convert.ToInt32((a.X - center.X) * (b.Y - center.Y) - (b.X - center.X) * (a.Y - center.Y)); 10 if (det < 0) 11 return true; 12 if (det > 0) 13 return false; 14 //向量OA和向量OB共线,以距离判断大小 15 double d1 = (a.X - center.X) * (a.X - center.X) + (a.Y - center.Y) * (a.Y - center.Y); 16 double d2 = (b.X - center.X) * (b.X - center.Y) + (b.Y - center.Y) * (b.Y - center.Y); 17 return d1 > d2; 18 }
每多学一点知识,就少写一行代码