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];
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user