最大间隙问题

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值