MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / median

Method median

src/main/java/com/thealgorithms/maths/Median.java:36–48  ·  view source on GitHub ↗

Calculates the median of an array of integers. The array is sorted internally, so the original order is not preserved. For arrays with an odd number of elements, returns the middle element. For arrays with an even number of elements, returns the average of the two middle elements. @param values the

(int[] values)

Source from the content-addressed store, hash-verified

34 * @throws IllegalArgumentException if the input array is empty or null
35 */
36 public static double median(int[] values) {
37 if (values == null || values.length == 0) {
38 throw new IllegalArgumentException("Values array cannot be empty or null");
39 }
40
41 Arrays.sort(values);
42 int length = values.length;
43 if (length % 2 == 0) {
44 return (values[length / 2] + values[length / 2 - 1]) / 2.0;
45 } else {
46 return values[length / 2];
47 }
48 }
49}

Calls 1

sortMethod · 0.65