Fix empty input handling in FindMax (#4206)

This commit is contained in:
Piotr Idzik 2023-05-28 22:45:13 +02:00 committed by GitHub
parent 4f15149804
commit 96c1a96647
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 8 deletions

View File

@ -24,16 +24,20 @@ public class FindMax {
} }
/** /**
* find max of array * @brief finds the maximum value stored in the input array
* *
* @param array the array contains element * @param array the input array
* @return max value of given array * @exception IllegalArgumentException input array is empty
* @return the maximum value stored in the input array
*/ */
public static int findMax(int[] array) { public static int findMax(int[] array) {
int max = array[0]; if (array.length == 0) {
for (int i = 1; i < array.length; ++i) { throw new IllegalArgumentException("array must be non-empty.");
if (array[i] > max) { }
max = array[i]; int max = Integer.MIN_VALUE;
for (final var value : array) {
if (value > max) {
max = value;
} }
} }
return max; return max;

View File

@ -1,16 +1,41 @@
package com.thealgorithms.maths; package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
public class FindMaxTest { public class FindMaxTest {
@Test @Test
public void testFindMaxValue() { public void testFindMax0() {
assertEquals( assertEquals(
10, 10,
FindMax.findMax(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) FindMax.findMax(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })
); );
} }
@Test
public void testFindMax1() {
assertEquals(
7,
FindMax.findMax(new int[] { 6, 3, 5, 1, 7, 4, 1 })
);
}
@Test
public void testFindMax2() {
assertEquals(
10,
FindMax.findMax(new int[] { 10, 0 })
);
}
@Test
public void testFindMaxThrowsExceptionForEmptyInput() {
assertThrows(
IllegalArgumentException.class,
() -> FindMax.findMax(new int[]{})
);
}
} }