style: handle empty input array in FindMin.findMin (#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
This commit is contained in:
Piotr Idzik 2023-05-28 13:08:44 +02:00 committed by GitHub
parent e14b30b88c
commit 4f15149804
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 7 deletions

View File

@ -24,16 +24,20 @@ public class FindMin {
} }
/** /**
* Find the minimum number of an array of numbers. * @brief finds the minimum value stored in the input array
* *
* @param array the array contains element * @param array the input array
* @return min value * @exception IllegalArgumentException input array is empty
* @return the mimum value stored in the input array
*/ */
public static int findMin(int[] array) { public static int findMin(int[] array) {
int min = 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] < min) { }
min = array[i]; int min = Integer.MAX_VALUE;
for (final var value : array) {
if (value < min) {
min = value;
} }
} }
return min; return min;

View File

@ -1,6 +1,7 @@
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;
@ -23,4 +24,17 @@ public class FindMinTest {
public void test2() { public void test2() {
assertEquals(0, FindMin.findMin(new int[] { 0, 192, 384, 576 })); assertEquals(0, FindMin.findMin(new int[] { 0, 192, 384, 576 }));
} }
@Test
public void test3() {
assertEquals(0, FindMin.findMin(new int[] { 10, 10, 0, 10 }));
}
@Test
public void testFindMinThrowsExceptionForEmptyInput() {
assertThrows(
IllegalArgumentException.class,
() -> FindMin.findMin(new int[]{})
);
}
} }