Here I have written code for finding median of two sorted arrays:
#include<iostream>
using namespace std;
#define L 5
#define M 6
const int N=L+M;
int A[1000];//define 1 indexed aarray
int B[1000];
int max(int c,int d){
return (c>=d)?c:d;
}
int min(int c,int d)
{
return (c<=d)?c:d;
}
void read(){
cout<<" enter A array "<<endl;
for (int i=1;i<=L;i++)
cin>>A[i];
cout<<endl;
cout<<"enter B array "<<endl;
for (int i=1;i<=M;i++)
cin>>B[i];
cout<<endl;
}
int median(int a[],int b[],int left,int right){
if (left>right) {
return median(b,a,max(1,(N/2)-L),min(M,N/2));
}
int i=int(left+right)/2;
int j=int(N/2)+i;
if((j==0 || a[i]>b[j]) && (j==M || a[i]<=b[j+1])){
return a[i];
}
else
{
if((j==0 || a[i]>b[j]) &&(j!=M && a[i]>b[j+1]))
return median(a,b,left,i-1);
}
return median(a,b,i+1,right);
}
int main(){
return 0;
}
My question is what could be left and right values? It is from introduction to algorithms, I just don’t understand what are values of left and right variables?
I have defined left and right as 1 and N and tested with following arrays:
3 5 7 9 11 13
1 2 4 8 10
Answer is 13, which is not correct sure, what is wrong?
The homework problem you cited in a comment has what looks to be a pretty good explanation of
leftandright, including the starting values for them:If you work through the algorithm on paper with small arrays, it should become more clear what’s going on. The algorithm converges in only a few steps if your arrays are smaller than a total of say 16 elements, so it should be quite workable on paper.