寻找两个等长有序序列的中位数(分治法,C/C++)

#include <stdio.h>
#include <xmath.h>

#include <algorithm>

int midnum(int a[], int s1, int t1, int b[], int s2, int t2);

void prepart(int &s, int &t);

void postpart(int &s, int &t);

int main(){
    int a[]={11,13,15,17,19};
    int b[]={2,4,6,8,20};

    printf("the median:%d",midnum(a,0,4,b,0,4));
}

//求两个有序序列的中位数
int midnum(int a[], int s1, int t1, int b[], int s2, int t2) {
    int m1,m2;
    if(s1==t1&&s2==t2)
        return a[s1]<b[s2]?a[s1]:b[s2];//两个序列只有一个元素时返回较小的
    else{
        m1=(s1+t1)/2;       //求a的中位数
        m2=(s2+t2)/2;       //求b的中位数
        if(a[m1]==b[m2])    //两个中位数相等时返回该中位数
            return b[m1];
        else if(a[m1]>b[m2]){   //当a[m1]>b[m2]时取a的前半部分,b的后半部分
            prepart(s1,t1);
            postpart(s2,t2);
            return midnum(a,s1,t1,b,s2,t2);
        } else{                              //当a[m1]>b[m2]时取b的前半部分,a的后半部分
            postpart(s1,t1);
            postpart(s2,t2);
            return midnum(a,s1,t1,b,s2,t2);
        }
    }
    return 0;
}

void postpart(int &s, int &t) {     //求序列后半子序列
    int m=(s+t)/2;
    if((s+t)%2==0)                  //序列中有奇数个元素
        s=m;
    else                            //序列中有偶数个元素。
        s=m+1;
}

void prepart(int &s, int &t) {  //求序列前半子序列
    int m=(s+t)/2;
    t=m;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值