如代码,代码我加了一点注释。
#include<iostream>
using namespace std;
double fun(int A[],int m,int B[],int n);
int main()
{
int A[]={1,1,1};
int B[]={2,2,3,4};
double X=fun(A,3,B,4);
cout<<"X="<<X<<endl;
getchar();
return 1;
}
double fun(int A[],int m,int B[],int n)
{
//中位数是排序好的数的中间位置的数,本代码的思想是,对两个排序的数组,每次比较两个数,把小者先取出。
//比如:A[0]比B[0]小,则A[0]先取出,相当于第三个数组的第一个元素产生了,以此类推,一直取出中间个数即中位数。
int temp = 0;
if(A[0]>A[m-1])//确认是升序
{
for(int i=0; i<m/2; i++)
{
temp=A[i];
A[i] = A[m-i-1];
A[m-i-1]=temp;
}
}
if(B[0]>B[n-1])//确认是升序
{
for(int i=0; i<n/2; i++)
{
temp=B[i];
B[i] = B[m-i-1];
B[m-i-1]=temp;
}
}
int t = (m+n)/2+1;//中位数一定位于第t的位置附近,若是m+n是偶数则中位数是t-1;t-2的平均值。否则是第t-1的值
//方法一:定义两个变量始终保存最后弹出的两个值,知道最后保存t-1,t-2的值
int tmp0=0;
int tmp1=0;
//方法二:建立一个长度为t的数组,用于保存包括中位数及中位数之前的所有说。
int *C=new int[t];
//int C[t];
int i = 0;
int j = 0;
for(int k=0;k<t;k++)
{
if(i<m&&j<n)//保证不能越界
{
if(A[i]<B[j])//如果条件成立,这A数组取下一位,否则B数组取下一位
{
C[k]=A[i];
tmp0=tmp1;
tmp1=A[i];
i++;
}
else
{
C[k]=B[j];
tmp0=tmp1;
tmp1=B[j];
j++;
}
}
else if(i==m)//当A数组取到尾部
{
C[k]=B[j];
tmp0=tmp1;
tmp1=B[j];
j++;
}
else if(j==n)//当B数组取到尾部
{
C[k]=A[i];
tmp0=tmp1;
tmp1=A[i];
i++;
}
}
if((m+n)%2==0)//m+n为偶数
{
cout<<(tmp0+tmp1)/2.0<<endl;
return (C[t-1]+C[t-2])/2.0;
//return (tmp0+tmp1)/2.0;
}
else//m+n为基数
{
cout<<tmp1<<endl;
return C[t-1];
//return tmp1;
}
}