check if my program is correct

i should write a program to find the median of two sorted arrays
is it correct?

#include <iostream>
using namespace std;
double median (int array1[] , int m );
void selctionsort (int ary[] , int y);
void main ()
{
const int p=3;
const int c=5;

int nums1 [p]={5,1,13};
int nums2 [c]={2,9,8,0,6};
selctionsort(nums1,p);
selctionsort(nums2,c);

cout<<"find the median of this two arrays"<<endl;
double median2;
median2=(median(nums1,p)+median(nums2,c))/2;
cout<<median2<<endl;

system ("pause");

}

void selctionsort (int ary[] , int y)
{

int min , swap;
for ( int j=0;j<y;j++)
{
min=j;
//a function to find the smallest number as an index not the real number.
for (int i=j;i<y;i++)

{
if(ary[min]>ary[i])
min=i;
}
//swap function
swap=ary[j];
ary[j]=ary[min];
ary[min]=swap;


}



}

double median (int array1[], int m )
{
int i =m/2;
const int swap=i;
int s = m/2;
int r = s-1;

int med;
if (m%2!=0)
med=array1[swap];
else
{

const int l=s;
const int b=r;
med=(array1[s]+array1[r])/2;
}
return med;
}
I believe the median is the physical middle value of a sorted array.
eg size of the array / 2 (there may be 2 values, both valid, for even sized array, pick one, most pick /2 and call it good). If its odd you want the exact middle value.

you have way too much code.
double median(int *a, int size)
{return a[size/2]; //not quite, but finish it from here ... }

it should literally be about 3 lines of code when you get it set up like you want it.
eg if (size%2) return blah ; return other blah; is all you need.
Last edited on
But what does it mean to find the "median of two arrays"?
One after the other?
Both joined together?

And the median of an array with an even number of elements is the average of the elements at size/2 and size/2 - 1.

Also, to calculate the average of two integers you need to add them together and then divide by 2.0 (not 2, which would just be integer division).
Topic archived. No new replies allowed.