Skip to content

Commit 96c1a96

Browse files
authored
Fix empty input handling in FindMax (TheAlgorithms#4206)
1 parent 4f15149 commit 96c1a96

File tree

2 files changed

+37
-8
lines changed

2 files changed

+37
-8
lines changed

src/main/java/com/thealgorithms/maths/FindMax.java

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,20 @@ public static void main(String[] args) {
2424
}
2525

2626
/**
27-
* find max of array
27+
* @brief finds the maximum value stored in the input array
2828
*
29-
* @param array the array contains element
30-
* @return max value of given array
29+
* @param array the input array
30+
* @exception IllegalArgumentException input array is empty
31+
* @return the maximum value stored in the input array
3132
*/
3233
public static int findMax(int[] array) {
33-
int max = array[0];
34-
for (int i = 1; i < array.length; ++i) {
35-
if (array[i] > max) {
36-
max = array[i];
34+
if (array.length == 0) {
35+
throw new IllegalArgumentException("array must be non-empty.");
36+
}
37+
int max = Integer.MIN_VALUE;
38+
for (final var value : array) {
39+
if (value > max) {
40+
max = value;
3741
}
3842
}
3943
return max;
Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,41 @@
11
package com.thealgorithms.maths;
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
45

56
import org.junit.jupiter.api.Test;
67

78
public class FindMaxTest {
89

910
@Test
10-
public void testFindMaxValue() {
11+
public void testFindMax0() {
1112
assertEquals(
1213
10,
1314
FindMax.findMax(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })
1415
);
1516
}
17+
18+
@Test
19+
public void testFindMax1() {
20+
assertEquals(
21+
7,
22+
FindMax.findMax(new int[] { 6, 3, 5, 1, 7, 4, 1 })
23+
);
24+
}
25+
26+
@Test
27+
public void testFindMax2() {
28+
assertEquals(
29+
10,
30+
FindMax.findMax(new int[] { 10, 0 })
31+
);
32+
}
33+
34+
@Test
35+
public void testFindMaxThrowsExceptionForEmptyInput() {
36+
assertThrows(
37+
IllegalArgumentException.class,
38+
() -> FindMax.findMax(new int[]{})
39+
);
40+
}
1641
}

0 commit comments

Comments
 (0)