mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-12-19 07:00:35 +08:00
refactor: improving Median (#6404)
refactor: improving Median Co-authored-by: Deniz Altunkapan <93663085+DenizAltunkapan@users.noreply.github.com>
This commit is contained in:
committed by
GitHub
parent
b45fd2a656
commit
31bf130e9e
@@ -13,8 +13,13 @@ public final class 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];
|
||||
|
||||
Reference in New Issue
Block a user