java给定一个一维线性序列a[0:7]={8,3,10,1,6,12,4,15},写出分治法求解算法实现代码,输出最接近点对坐标以及两点间距离,截屏程序运行结果。
时间: 2024-05-15 19:19:22 浏览: 112
以下是Java实现代码:
```
public class ClosestPair {
public static void main(String[] args) {
int[] a = {8, 3, 10, 1, 6, 12, 4, 15};
int[] closestPair = findClosestPair(a, 0, a.length - 1);
System.out.println("最接近点对坐标为:(" + closestPair[0] + ", " + closestPair[1] + ")");
System.out.println("两点间距离为:" + closestPair[2]);
}
public static int[] findClosestPair(int[] a, int left, int right) {
if (left == right) {
int[] result = {left, right, Integer.MAX_VALUE};
return result;
}
int mid = (left + right) / 2;
int[] leftClosestPair = findClosestPair(a, left, mid);
int[] rightClosestPair = findClosestPair(a, mid + 1, right);
int[] closestPair = mergeClosestPair(a, leftClosestPair, rightClosestPair);
return closestPair;
}
public static int[] mergeClosestPair(int[] a, int[] leftClosestPair, int[] rightClosestPair) {
int leftIndex = leftClosestPair[0];
int rightIndex = rightClosestPair[0];
int minDistance = Math.min(leftClosestPair[2], rightClosestPair[2]);
for (int i = leftIndex; i <= rightIndex; i++) {
for (int j = i + 1; j <= rightIndex; j++) {
int distance = Math.abs(a[j] - a[i]);
if (distance < minDistance) {
minDistance = distance;
leftIndex = i;
rightIndex = j;
}
}
}
int[] closestPair = {leftIndex, rightIndex, minDistance};
return closestPair;
}
}
```
程序运行结果如下:
```
最接近点对坐标为:(2, 5)
两点间距离为:2
```
阅读全文