找众数和重数

1.算法基本思想
分治法求众数和重数:利用分治算法先划分为若干个子问题,递归求解每一个子问题,最后将子问题合并,从而求解到整个问题的解。
2.主要数据结构及其作用
一维数组:存储并记录数据
3.测试用例
测试用例
4.实验结果截图
测试用例1
测试用例1
测试用例2
测试用例2
测试用例3

测试用例3
5.代码实现

#include<iostream>
using namespace std;
void MergeSort(int a[],int l,int r)
{
    if(l==r) return ;
    int mid=(l+r)/2;
    MergeSort(a,l,mid);
    MergeSort(a,mid+1,r);
    int lp=l,rp=mid+1,np=l;
    int temp[r+1];
    while(lp<=mid && rp<=r)
    {
        if(a[lp]>=a[rp])
        {
            temp[np++]=a[rp++];
        }
        else
        {
            temp[np++]=a[lp++];
        }
    }
    while(lp<=mid) temp[np++]=a[lp++];
    while(rp<=r) temp[np++]=a[rp++];
    for(int i=l; i<=r; i++) a[i]=temp[i];
}
void Findx(int a[],int low,int high,int &x,int &times)
{
    if(low>=high) return;
    else
    {
        int x1=0,x2=0,times1=0,times2=0;
        int mid=(low+high)/2;
        Findx(a,low,mid,x1,times1);
        Findx(a,mid+1,high,x2,times2);
        int i=mid-1;
        int j=mid+1;
        times=1;
        x=a[mid];
        while(i>=low&&a[mid]==a[i])
        {
            i--;
            times++;
        }
        while(j<=high&&a[mid]==a[j])
        {
            j++;
            times++;
        }
        if(times<=times1)
        {
            x=x1;
            times=times1;
        }
        if(times<=times2)
        {
            x=x2;
            times=times2;
        }
    }
}
int main()
{
    int n;
    cout<<"请输入需要输入的元素的个数:"<<endl;
    cin>>n;
    int a[n],x,times;
    cout<<"请输入"<<n<<"个元素:"<<endl;
    for(int i=0; i<n; i++)
        cin>>a[i];
    MergeSort(a,0,n-1);
    Findx(a,0,n-1,x,times);
    cout<<"众数是: "<<x<<" 重数是: "<<times<<endl;
    return 0;
}
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二琳爱吃肉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值