资源简介
使用分治算法实现寻找n个点中最邻近点的距离的平方。时间复杂度O(nlogn).
代码片段和文件信息
#include
#include
struct Point_X{
float x;
float y;
};
struct Point_Y{
int index;
float x;
float y;
};
void swap(Point_X *aPoint_X *b);
int CountDistance(Point_X aPoint_X b);
void Closest_Pair(Point_X x[]int sizePoint_X &aPoint_X &bint &MinDistance);
void Closest_Pair_Rec(Point_X x[]Point_Y y[]int lowint highPoint_X &aPoint_X &bint &MinDistance);
void swap(Point_X *aPoint_X *b)
{
Point_X temp=*a;
*a=*b;
*b=temp;
}
int CountDistance(Point_X aPoint_X b)
{
return (int)pow(a.x-b.x2)+pow(a.y-b.y2);
}
void merge(Point_X L1[]Point_X L2[]const int leftconst int midconst int right)
{
int k=0;
for(k=left;k<=right;k++)
L2[k]=L1[k];
int s1=lefts2=mid+1t=left;//s1s2分别是L2的两个表的检测指针t是L1中的存放指针
while(s1<=mid && s2<=right) //两个表都不为空时
if(L2[s1].x<=L2[s2].x) //两个表的表头元素通过比较把较小的元素加入到存放表L1中
L1[t++]=L2[s1++];
else
L1[t++]=L2[s2++];
while(s1 <= mid) //若第一个表未检查完成把已排好序的未加入部分复制到L1中
L1[t++]=L2[s1++];
while(s2 <= right) //若第二个表未检查完成
L1[t++]=L2[s2++];
}
void MergeSort(Point_X L[]Point_X L2[]int leftint right)
{
if(left>=right)
return;
int mid=(left+right)/2; //从中间划分为两个子序列
MergeSort(LL2leftmid); //对左侧子序列进行递归排序
MergeSort(LL2mid+1right);//对右侧子序列进行递归排序
merge(LL2leftmidright); //合并
}
void Closest_Pair(Point_X x[]int sizePoint_X &aPoint_X &bint &MinDistance){
if(size<2)
{
MinDistance=0;
return;
}
Point_X *px=new Point_X[size];
MergeSort(xpx0size-1);
Point_Y *y=new Point_Y[size];
for(int i=0;i {
y[i].index=i;
y[i].x=x[i].x;
y[i].y=x[i].y;
}
Closest_Pair_Rec(xy0size-1abMinDistance);
delete y;
}
void Closest_Pair_Rec(Point_X x[]Point_Y y[]int lowint highPoint_X &aPoint_X &bint &MinDistance){
Point_X albl
- 上一篇:C/C++实现FAT文件系统的读写
- 下一篇:Qt5Twain.rar
评论
共有 条评论