Paul D Paul D - 6 months ago 9
Java Question

Median method returning higher value median

So im writing a method in which it finds the median of an n-numbered array. If the array has an odd number of elements it works fine, however if the array has an even number of elements, I want the program to output the higher of the 2 middle numbers rather than the lower of the 2. At the current moment, my code is outputting the lower number. This is the code:

public Long getMedian() {

long median = 0;

Arrays.sort(elements);

if (length % 2 != 0) {
median = elements[length/2];
} if (length % 2 == 0) {
median = ((elements[length/2]) + (elements[(length/2) - 1])) / 2;
median++;
}

return median;
}


For example, if the array with numbers
[30 41 45 50]
was inputted, the median would be 45, not 41. Please help!

kan kan
Answer

Surprisingly it is most straightforward solution:

public Long getMedian() {
    Arrays.sort(elements);

    return elements[elements.length / 2];
}
Comments