refactor: improving Median (#6404)

refactor: improving Median

Co-authored-by: Deniz Altunkapan <93663085+DenizAltunkapan@users.noreply.github.com>
This commit is contained in:
Oleksandr Klymenko
2025-07-20 11:21:46 +03:00
committed by GitHub
parent b45fd2a656
commit 31bf130e9e
2 changed files with 12 additions and 0 deletions

View File

@@ -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];

View File

@@ -1,6 +1,7 @@
package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
@@ -34,4 +35,10 @@ public class MedianTest {
int[] arr = {-27, -16, -7, -4, -2, -1};
assertEquals(-5.5, Median.median(arr));
}
@Test
void medianEmptyArrayThrows() {
int[] arr = {};
assertThrows(IllegalArgumentException.class, () -> Median.median(arr));
}
}