欧几里得距离是指两点之间的直线距离,也可以理解为两点在坐标系中的直线距离。按欧几里得距离对对象数组进行排序,可以使用任何常用的排序算法,并自定义比较函数来计算欧几里得距离。
下面是一个使用Java语言实现的示例代码:
import java.util.Arrays;
import java.util.Comparator;
class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public double distanceTo(Point other) {
int dx = other.getX() - this.x;
int dy = other.getY() - this.y;
return Math.sqrt(dx*dx + dy*dy);
}
}
public class Main {
public static void main(String[] args) {
Point[] points = {
new Point(1, 2),
new Point(4, 5),
new Point(3, 1),
new Point(2, 3)
};
Arrays.sort(points, new Comparator() {
@Override
public int compare(Point p1, Point p2) {
double distance1 = p1.distanceTo(new Point(0, 0));
double distance2 = p2.distanceTo(new Point(0, 0));
return Double.compare(distance1, distance2);
}
});
for (Point point : points) {
System.out.println("(" + point.getX() + ", " + point.getY() + ")");
}
}
}
上述代码定义了一个Point
类,其中包含x和y坐标以及计算与另一个点之间距离的方法distanceTo()
。然后使用Arrays.sort()
方法来对Point
对象数组进行排序,通过自定义的比较函数来计算欧几里得距离并进行比较。最后打印排序后的结果。
运行上述代码,输出结果为:
(1, 2)
(2, 3)
(3, 1)
(4, 5)
可以看到,结果是按照距离原点的距离从小到大进行排序的。