#include "stdio.h"
#include "string.h"
#include "iostream"
#include "fstream"
using namespace std;
const int N = 100;
int n; //数的个数
double data[100];
double high[N];
double low[N];
double count[N];
//返回数组中最大值
template<class Type>
int maxi(Type data[])
{
int i;
Type max = data[0];
for(i=1; i<n; i++)
if(max < data[i])
max = data[i];
return max;
}
//返回数组中最小值
template<class Type>
int mini(Type data[])
{
int i;
Type min = data[0];
for(i=1; i<n; i++)
if(min > data[i])
min = data[i];
return min;
}
template<class Type>
Type maxgap(Type data[])
{
Type max = maxi(data);
Type min = mini(data);
//分割区间[min, max],产生n-1个桶,每个桶中用high[i]和low[i]分别
//存储分配给桶i的数中的最大数和最小数
int i;
for(i=0; i<n; i++)
{
low[i] = max;
high[i] = min;
count[i] = 0;
}
//将n个数装入n-1个桶
int gap = (max - min) / (n - 1); //每个桶的大小
for(i=0; i<n; i++)
{
int bucket = (int)((data[i]-min)/gap) + 1; //被分配到哪个桶中
count[bucket]++;
if(data[i]<low[bucket]) low[bucket] = data[i];
if(data[i]>high[bucket]) high[bucket] = data[i];
}
//除了最大数和最小数外,剩余n-2个数装入了n-1个桶中,由鸽舍原理
//必有一个桶是空的,所以最大间隙必然产生于相邻的两个桶之间
Type left = high[0];
Type max_gap = 0;
for(i=1; i<n-1; i++)
if(count[i])
if(low[i]-left > max_gap)
{
max_gap = low[i] - left;
left = high[i];
}
return max_gap;
}
int main()
{
ifstream fin("gap.txt");
fin >> n;
int i = 0;
cout << n << "个实数分别为:\n";
while(!fin.eof())
{
fin >> data[i];
cout << data[i++] << " ";
}
double max = maxgap(data);
cout << "\n最大间隙为:" << max << endl;
return 0;
}
gap.txt
5
2.3 3.1 7.5 1.5 6.3