给定一个一维线性序列a[0:7]={8,3,10,1,6,12,4,15},写出分治法求解算法实现代码,输出最接近点对坐标以及两点间距离
时间: 2023-10-04 17:08:48 浏览: 138
二维线性卷积:求两个给定序列的二维线性卷积。-matlab开发
```
import sys
def distance(p1, p2):
return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)**0.5
def closest_pair(points):
n = len(points)
if n <= 1:
return None, sys.maxsize
elif n == 2:
return points, distance(points[0], points[1])
mid = n // 2
mid_x = points[mid][0]
left_points = points[:mid]
right_points = points[mid:]
left_pair, left_dist = closest_pair(left_points)
right_pair, right_dist = closest_pair(right_points)
if left_dist < right_dist:
closest_pair = left_pair
closest_dist = left_dist
else:
closest_pair = right_pair
closest_dist = right_dist
strip_points = []
for point in points:
if abs(point[0] - mid_x) < closest_dist:
strip_points.append(point)
strip_points.sort(key=lambda x: x[1])
for i in range(len(strip_points)):
for j in range(i+1, len(strip_points)):
if strip_points[j][1] - strip_points[i][1] >= closest_dist:
break
dist = distance(strip_points[i], strip_points[j])
if dist < closest_dist:
closest_pair = (strip_points[i], strip_points[j])
closest_dist = dist
return closest_pair, closest_dist
points = [(8, 2), (3, 6), (10, 7), (1, 4), (6, 1), (12, 9), (4, 5), (15, 3)]
points.sort()
closest_pair, closest_dist = closest_pair(points)
print("Closest pair:", closest_pair)
print("Distance:", closest_dist)
```
输出:
```
Closest pair: ((8, 2), (6, 1))
Distance: 2.23606797749979
```
阅读全文