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

refactor: improvingMedian#6404

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
alxkm wants to merge1 commit intoTheAlgorithms:master
base:master
Choose a base branch
Loading
fromalxkm:refactor/Median
Open
Show file tree
Hide file tree
Changes fromall 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 deletionssrc/main/java/com/thealgorithms/maths/Median.java
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletionssrc/test/java/com/thealgorithms/maths/MedianTest.java
View file
Open in desktop
Original file line numberDiff line numberDiff 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 DownExpand 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));
}
}
Loading

[8]ページ先頭

©2009-2025 Movatter.jp