Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit31bf130

Browse files
refactor: improvingMedian (#6404)
refactor: improving MedianCo-authored-by: Deniz Altunkapan <93663085+DenizAltunkapan@users.noreply.github.com>
1 parentb45fd2a commit31bf130

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
publicstaticdoublemedian(int[]values) {
19+
if (values ==null ||values.length ==0) {
20+
thrownewIllegalArgumentException("Values array cannot be empty or null");
21+
}
22+
1823
Arrays.sort(values);
1924
intlength =values.length;
2025
returnlength %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
packagecom.thealgorithms.maths;
22

33
importstaticorg.junit.jupiter.api.Assertions.assertEquals;
4+
importstaticorg.junit.jupiter.api.Assertions.assertThrows;
45

56
importorg.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+
voidmedianEmptyArrayThrows() {
41+
int[]arr = {};
42+
assertThrows(IllegalArgumentException.class, () ->Median.median(arr));
43+
}
3744
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp