How can I calculate the median of an unorder Java list?
Here is the code I have written so far:
public class MockTest1 {
/*
given a random list of integers, find the median e.g. given the list [1, 4, 2, 3, 5] the median is 3
*/
public static void main(String[] args) {
List<Integer> array = List.of(1, 3, 4, 5, 2);
System.out.println(getMedian(array));
}
public static int getMedian(List<Integer> arr) {
ArrayList<Integer> list = new ArrayList<>(arr);
Collections.sort(list);
double length = (double) list.size();
int med = (int) Math.ceil(length / 2);
return list.get(med - 1);
}
}
I converted the list to an arraylist to make it mutable.
For the example I'm using, i.e., [1, 3, 4, 5, 2] I am getting an ouput of 4 instead of 3, my concensus from this is that the list is not remaining sorted when I call the get method, how do I solve this problem?