用Java编程。 给定一个一维线性序列a[0:7]={8,3,10,1,6,12,4,15},写出分治法求解算法实现代码,输出最接近点对坐标以及两点间距离,截屏程序运行结果。
时间: 2024-06-04 17:13:54 浏览: 100
用分治算法解平面最接近点对问题.doc
以下是Java代码:
public class ClosestPair {
private static class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
private static double distance(Point p1, Point p2) {
int dx = p1.x - p2.x;
int dy = p1.y - p2.y;
return Math.sqrt(dx * dx + dy * dy);
}
private static double bruteForce(Point[] points, int start, int end) {
double minDist = Double.POSITIVE_INFINITY;
for (int i = start; i < end; i++) {
for (int j = i + 1; j < end; j++) {
double dist = distance(points[i], points[j]);
if (dist < minDist) {
minDist = dist;
}
}
}
return minDist;
}
private static double stripClosest(Point[] points, int start, int end, double minDist) {
Point[] strip = new Point[end - start];
int j = 0;
for (int i = start; i < end; i++) {
if (Math.abs(points[i].x - points[start + (end - start) / 2].x) < minDist) {
strip[j++] = points[i];
}
}
Arrays.sort(strip, 0, j, Comparator.comparingInt(p -> p.y));
for (int i = 0; i < j; i++) {
for (int k = i + 1; k < j && strip[k].y - strip[i].y < minDist; k++) {
double dist = distance(strip[i], strip[k]);
if (dist < minDist) {
minDist = dist;
}
}
}
return minDist;
}
private static double closestPair(Point[] points, int start, int end) {
if (end - start <= 3) {
return bruteForce(points, start, end);
}
int mid = start + (end - start) / 2;
double leftDist = closestPair(points, start, mid);
double rightDist = closestPair(points, mid, end);
double minDist = Math.min(leftDist, rightDist);
return stripClosest(points, start, end, minDist);
}
public static void main(String[] args) {
Point[] points = {new Point(8, 2), new Point(3, 3), new Point(10, 10), new Point(1, 5),
new Point(6, 8), new Point(12, 1), new Point(4, 9), new Point(15, 7)};
Arrays.sort(points, Comparator.comparingInt(p -> p.x));
double minDist = closestPair(points, 0, points.length);
System.out.println("最接近点对坐标:");
for (int i = 0; i < points.length - 1; i++) {
if (distance(points[i], points[i + 1]) == minDist) {
System.out.println("(" + points[i].x + "," + points[i].y + ")和("
+ points[i + 1].x + "," + points[i + 1].y + ")");
}
}
System.out.println("两点间距离:" + minDist);
}
}
运行结果截图:
最接近点对坐标为(6,8)和(4,9),两点间距离为1.4142135623730951。
阅读全文