如何计算无序 Java 列表的中位数?
这是我到目前为止编写的代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我将列表转换为数组列表以使其可变。
对于我正在使用的示例,即 …