众数问题

#include "iostream"
#include "algorithm"
#include "fstream"
using namespace std;

//数组a[l,h]中,将小于a[l]的放其左,大于a[l]的放其右
int partition(int y[], int l, int r)
{  
    int i = l, j = r+1;  
    int x = y[l];  
    while(true)
    {  
         while(y[++i] < x);  
         while(y[--j] > x);  
         if(i>=j) 
             break;  
         swap(y[i], y[j]);  
    }  
    y[l] = y[j];  
    y[j] = x;  
    return j;  
}

//统计a[mid]出现的次数
//minIndex记录a[mid]最左边下标,maxIndex记录a[mid]最右边下标
int modeIndex(int a[], int &mid, int l, int h, int &minIndex, int &maxIndex)
{
    int left = mid;
    int right = mid;
    while(a[--left] == a[mid] && left>=l);
    while(a[++right] == a[mid] && right<=h);
    left++;
    right--;
    minIndex = left;
    maxIndex = right;
    return maxIndex - minIndex + 1;
}

//number为a[l,h]的众数,count为重数
void mode(int a[], int l, int h, int &number, int &count)
{
    int index = partition(a, l, h); //众数下标
    int minIndex, maxIndex;
    int num = modeIndex(a, index, l, h, minIndex, maxIndex);  //统计a[index]出现的次数num
    if(num > count)  //如果a[mid]出现次数比之前找到的众数出现次数多
    {
        number = a[index];  //更新众数
        count = num;  //更新众数的个数
    }
    if(num < minIndex-l+1)  //如果a[index]左边的数大于num,向左递归
        mode(a, l, minIndex-1, number, count);
    if(num < h-maxIndex+1) //如果a[index]右边的数大于num,向右递归
        mode(a, maxIndex+1, h, number, count);
}

int main()
{
    int n;
    ifstream fin("number.txt");
    fin >> n;
    cout << "元素个数为:" << n << endl;
    int *a = new int[n+1];
    cout << "各元素为:\n";
    for(int i=1; i<=n; i++)
    {
        fin >> a[i];
        cout << a[i] << " ";
    }
    sort(a, a+n);
    cout << endl;
    int count = 0;
    int number;
    mode(a, 1, n, number, count);
    cout << "众数为:" << number << endl;
    cout << "重数为:" << count << endl; 
    fin.close();
    return 0;
} 

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值