下面是一个示例代码,演示如何按照顺时针对点进行排序:
using System;
using System.Collections.Generic;
public class Point
{
public int X { get; set; }
public int Y { get; set; }
public Point(int x, int y)
{
X = x;
Y = y;
}
// 计算点到原点的极角
private double GetPolarAngle()
{
return Math.Atan2(Y, X);
}
// 按照极角比较两个点
public static int CompareByPolarAngle(Point p1, Point p2)
{
double angle1 = p1.GetPolarAngle();
double angle2 = p2.GetPolarAngle();
if (angle1 < angle2)
return -1;
else if (angle1 > angle2)
return 1;
else
return 0;
}
public override string ToString()
{
return $"({X}, {Y})";
}
}
public class Program
{
public static void Main(string[] args)
{
List points = new List
{
new Point(0, 0),
new Point(1, 1),
new Point(-1, 1),
new Point(-1, -1),
new Point(1, -1)
};
points.Sort(Point.CompareByPolarAngle);
foreach (var point in points)
{
Console.WriteLine(point);
}
}
}
输出结果为:
(0, 0)
(1, -1)
(1, 1)
(-1, 1)
(-1, -1)
以上代码定义了一个Point
类,包含X
和Y
属性以及计算极角的方法GetPolarAngle
。然后定义了一个静态的比较方法CompareByPolarAngle
,用于按照极角比较两个点。最后在Main
方法中创建了一个点的列表,并使用Sort
方法按照极角对点进行排序。最后输出排序后的点。
上一篇:按照数量显示结果列表
下一篇:按照顺序保留并集