Paul D - 1 year ago 65

Java Question

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]`

Answer Source

Surprisingly it is most straightforward solution:

```
public Long getMedian() {
Arrays.sort(elements);
return elements[elements.length / 2];
}
```