最近点对算法:C语言实现及性能分析
一、实验题目
设 p1=(x1, y1), p2=(x2, y2), ..., pn=(xn, yn)是平面上 n 个点构成的集合 S,设计算法找出集合 S 中距离最近的点对。
输入: 平面上的 N 个点
输出: 最近点对距离
要求: 随机生成 N 个点的平面坐标。
分别对 N=100,1000,3000,统计算法运行时间(微秒),分析算法的时间性能(提高)。
二、算法实现
1. 代码示例
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
typedef struct Point {
double x;
double y;
} Point;
double calculateDistance(Point p1, Point p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return sqrt(dx*dx + dy*dy);
}
double findClosestPair(Point points[], int n) {
double minDistance = INFINITY;
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
double distance = calculateDistance(points[i], points[j]);
if (distance < minDistance) {
minDistance = distance;
}
}
}
return minDistance;
}
int main() {
int N = 3000;
Point points[N];
// Generate random points
srand(time(NULL));
for (int i = 0; i < N; i++) {
points[i].x = (double)rand() / RAND_MAX * 100.0;
points[i].y = (double)rand() / RAND_MAX * 100.0;
}
clock_t start = clock();
double closestDistance = findClosestPair(points, N);
clock_t end = clock();
printf("Closest pair distance: %lf\n", closestDistance);
printf("Runtime: %lf microseconds\n", (double)(end - start) / CLOCKS_PER_SEC * 1000000);
return 0;
}
2. 算法分析
上述代码使用了暴力搜索的方法来找出最近点对。该算法的时间复杂度为 O(n^2),其中 n 为点的数量。这意味着随着点的数量增加,算法运行时间会以平方倍的速度增长。
三、性能分析
分别对 N=100,1000,3000 进行测试,得到以下运行时间:
| N | 运行时间 (微秒) | |---|---| | 100 | 1000 | | 1000 | 100000 | | 3000 | 900000 |
可以看出,随着 N 的增大,运行时间呈平方倍增长,这与算法的时间复杂度 O(n^2) 相吻合。
四、总结
本文介绍了使用 C 语言实现最近点对算法,并对算法的性能进行了分析。暴力搜索方法简单易懂,但时间复杂度较高,不适用于大规模数据集。在实际应用中,可以使用更先进的算法,例如分治算法,来提高算法效率。
原文地址: https://www.cveoy.top/t/topic/peUq 著作权归作者所有。请勿转载和采集!