Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/main/java/com/thealgorithms/maths/Median.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,13 @@ 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];
Expand Down
7 changes: 7 additions & 0 deletions src/test/java/com/thealgorithms/maths/MedianTest.java
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -34,4 +35,10 @@ void medianNegativeValues() {
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));
}
}