forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMedian.java
More file actions
27 lines (23 loc) · 781 Bytes
/
Median.java
File metadata and controls
27 lines (23 loc) · 781 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.thealgorithms.maths;
import java.util.Arrays;
/**
* Wikipedia: https://en.wikipedia.org/wiki/Median
*/
public final class Median {
private Median() {
}
/**
* Calculate average median
* @param values sorted numbers to find median of
* @return median of given {@code values}
* @throws IllegalArgumentException If the input array is empty or null.
*/
public static double median(int[] values) {
if (values == null || values.length == 0) {
throw new IllegalArgumentException("Values array cannot be empty or null");
}
Arrays.sort(values);
int length = values.length;
return length % 2 == 0 ? (values[length / 2] + values[length / 2 - 1]) / 2.0 : values[length / 2];
}
}