Search code examples
c++mathmedian

What is the median value is decimal?


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.


Solution

  • 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++).