只考虑y轴轴值为0,x轴可以变化,用分治法实现:
#include <iostream>
#include <algorithm>
using namespace std;
const double Max = 201230089058;
double nearest1(double *array, double low, double high, int count);
int main() {
int n;
cout<<"输入x轴座标数目:";
cin>>n;
double *p = new double[n];
cout<<"输入每个x轴值:";
for(int i = 0; i < n; i++) {
cin>>p[i];
}
sort(p, p + n);
cout <<"最近值为 = "<<nearest1(p, p[0], p[n - 1], n) << endl;
delete [] p;
return 0;
}
double nearest1(double *array, double low, double high, int count) {
// 求平均值
double sum = 0.0;
double average = 0.0;
double dis;
if(1 == count) {
return Max;
}
for (int i = 0; i < count; i++) {
sum += *(array + i);
}
average = sum / count;
// 将小于平均值的数和大于平均值的数
int j = 0;
for (; j < count; j++) {
if ((array[j] <= average) && (array[j + 1] >= average)) {
break;
}
}
dis = array[j + 1] - array[j];
double leftdis;
double rightdis;
leftdis = nearest1(array, array[0], array[j], j + 1);
rightdis = nearest1(array + j + 1,array[j + 1], array[count - 1], count - j -1);
dis = (dis <= leftdis) ? dis : leftdis;
dis = (dis <= rightdis) ? dis : rightdis;
return dis;
}