Skip to content

Commit 31bf130

Browse files
refactor: improving Median (TheAlgorithms#6404)
refactor: improving Median Co-authored-by: Deniz Altunkapan <[email protected]>
1 parent b45fd2a commit 31bf130

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

src/main/java/com/thealgorithms/maths/Median.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,13 @@ private Median() {
1313
* Calculate average median
1414
* @param values sorted numbers to find median of
1515
* @return median of given {@code values}
16+
* @throws IllegalArgumentException If the input array is empty or null.
1617
*/
1718
public static double median(int[] values) {
19+
if (values == null || values.length == 0) {
20+
throw new IllegalArgumentException("Values array cannot be empty or null");
21+
}
22+
1823
Arrays.sort(values);
1924
int length = values.length;
2025
return length % 2 == 0 ? (values[length / 2] + values[length / 2 - 1]) / 2.0 : values[length / 2];

src/test/java/com/thealgorithms/maths/MedianTest.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.thealgorithms.maths;
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
45

56
import org.junit.jupiter.api.Test;
67

@@ -34,4 +35,10 @@ void medianNegativeValues() {
3435
int[] arr = {-27, -16, -7, -4, -2, -1};
3536
assertEquals(-5.5, Median.median(arr));
3637
}
38+
39+
@Test
40+
void medianEmptyArrayThrows() {
41+
int[] arr = {};
42+
assertThrows(IllegalArgumentException.class, () -> Median.median(arr));
43+
}
3744
}

0 commit comments

Comments
 (0)