Skip to content

Commit 4f15149

Browse files
authored
style: handle empty input array in FindMin.findMin (TheAlgorithms#4205)
* tests: add test case with mininum not being at the beginning * style: throw IllegalArgumentException when input is empty * style: use enhanced for loop * docs: update doc-str
1 parent e14b30b commit 4f15149

File tree

2 files changed

+25
-7
lines changed

2 files changed

+25
-7
lines changed

src/main/java/com/thealgorithms/maths/FindMin.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 the minimum number of an array of numbers.
27+
* @brief finds the minimum value stored in the input array
2828
*
29-
* @param array the array contains element
30-
* @return min value
29+
* @param array the input array
30+
* @exception IllegalArgumentException input array is empty
31+
* @return the mimum value stored in the input array
3132
*/
3233
public static int findMin(int[] array) {
33-
int min = array[0];
34-
for (int i = 1; i < array.length; ++i) {
35-
if (array[i] < min) {
36-
min = array[i];
34+
if (array.length == 0) {
35+
throw new IllegalArgumentException("array must be non-empty.");
36+
}
37+
int min = Integer.MAX_VALUE;
38+
for (final var value : array) {
39+
if (value < min) {
40+
min = value;
3741
}
3842
}
3943
return min;

src/test/java/com/thealgorithms/maths/FindMinTest.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
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

@@ -23,4 +24,17 @@ public void test1() {
2324
public void test2() {
2425
assertEquals(0, FindMin.findMin(new int[] { 0, 192, 384, 576 }));
2526
}
27+
28+
@Test
29+
public void test3() {
30+
assertEquals(0, FindMin.findMin(new int[] { 10, 10, 0, 10 }));
31+
}
32+
33+
@Test
34+
public void testFindMinThrowsExceptionForEmptyInput() {
35+
assertThrows(
36+
IllegalArgumentException.class,
37+
() -> FindMin.findMin(new int[]{})
38+
);
39+
}
2640
}

0 commit comments

Comments
 (0)