-3

I'm writing a program to find the median of an array in CPP. I am not sure if I have a clear idea about what a median is. As far as I know, I've written my program to find median but when the array is even-numbered, I'm confused whether I should print the ceiling or ground value of division ofthe decimal output I get when I divide the middle two elements from the array.


using namespace std;

void findMedian(int sortedArray[], int N);
int main()
{
    int ip[4] = {1, 2, 5, 8};
    findMedian(ip, 4);
}

void findMedian(int sortedArray[], int N)
{

    int size = N;
    int median;
    if ((size % 2) != 0)
    {
        median = sortedArray[(size / 2)];
    }
    else
    {
        median = (sortedArray[(size / 2) - 1] + sortedArray[size / 2]) / 2;
    }
    cout << median;
}

Thanks in advance, also if anyone can give the literal purpose of finding a median, I'd appreciate and it'd help me not ask this question again when I have to deal with Median. Pardon my English.

Dev_noob
  • 53
  • 1
  • 9
  • 2
    [If there is an even number of observations, then there is no single middle value; the median is then usually defined to be the mean of the two middle values.](https://en.wikipedia.org/wiki/Median) In your case, the median would not be an integer number according to this definition, it would be 3.5. You can round it, but then you may get wrong result. Consider `{1,2,3,4}`, where median is anything between 2 and 3, but not 2 nor 3. – Daniel Langr Aug 08 '19 at 11:55
  • Thank you and that makes it clear. This program I wrote for a contest should only return a single integer and the question didn't mention anywhere regarding the corner cases. – Dev_noob Aug 08 '19 at 12:04
  • Then, it should be specified in the contest problem definition what the integer median of an even-sized array means. If it is not, then the definition is incomplete. – Daniel Langr Aug 08 '19 at 12:08
  • OT Beware that you have a namespace collision with [std::size](https://en.cppreference.com/w/cpp/iterator/size) – nada Aug 08 '19 at 12:08

1 Answers1

1

on odd array the median is unique, but in a even array there are two medians: the lower median (the one in (n/2)th position) and the upper median (the one in (n/2+1) th position). I usually always see that the lower median is used as "median" for even arrays.

In this case you need only one formula for even and odd arrays:

medianPosition = n/2; // integer division
median = sortedArray[medianPosition];

Note that it is true only for array where indices starts with zero (like C/C++).

CDF
  • 28
  • 5