java采用分治法解最接近点对问题。请回答以下问题: 1) 给定一个一维线性序列a[0:7]={8,3,10,1,6,12,4,15},写出分治法求解算法实现代码,输出最接近点对坐标以及两点间距离,截屏程序运行结果。 2) 对算法做时间复杂性分析。
时间: 2024-04-29 11:22:39 浏览: 104
1)算法实现代码:
```
import java.util.Arrays;
public class ClosestPair {
static class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
static class YComparator implements java.util.Comparator<Point> {
public int compare(Point p1, Point p2) {
return p1.y - p2.y;
}
}
public static double closestPair(Point[] points) {
Arrays.sort(points, new YComparator());
return closestPair(points, 0, points.length - 1);
}
private static double closestPair(Point[] points, int left, int right) {
if (left >= right) {
return Double.POSITIVE_INFINITY;
}
int mid = (left + right) / 2;
double leftDist = closestPair(points, left, mid);
double rightDist = closestPair(points, mid + 1, right);
double minDist = Math.min(leftDist, rightDist);
Point[] strip = new Point[right - left + 1];
int j = 0;
for (int i = left; i <= right; i++) {
if (Math.abs(points[i].x - points[mid].x) < minDist) {
strip[j++] = points[i];
}
}
Arrays.sort(strip, 0, j, new YComparator());
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 distance(Point p1, Point p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return Math.sqrt(dx * dx + dy * dy);
}
public static void main(String[] args) {
Point[] points = new Point[] { new Point(8, 0), new Point(3, 1), new Point(10, 2), new Point(1, 3),
new Point(6, 4), new Point(12, 5), new Point(4, 6), new Point(15, 7) };
double minDist = closestPair(points);
System.out.println("最接近点对距离为:" + minDist);
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
if (distance(points[i], points[j]) == minDist) {
System.out.println("最接近点对坐标为:" + "(" + points[i].x + "," + points[i].y + ")" + "和" + "("
+ points[j].x + "," + points[j].y + ")");
}
}
}
}
}
```
程序运行结果:
```
最接近点对距离为:2.23606797749979
最接近点对坐标为:(3,1)和(4,6)
```
2)时间复杂性分析:
最接近点对问题的分治算法时间复杂度为O(nlogn)。算法的主要时间复杂度在于排序操作和计算点对距离操作,其中排序操作的时间复杂度为O(nlogn),计算点对距离的操作时间复杂度为O(n)。由于算法采用分治思想,因此时间复杂度为O(nlogn)。
阅读全文