diff --git a/src/main/java/com/thealgorithms/maths/FindMin.java b/src/main/java/com/thealgorithms/maths/FindMin.java index e3be09e34..7764c1c04 100644 --- a/src/main/java/com/thealgorithms/maths/FindMin.java +++ b/src/main/java/com/thealgorithms/maths/FindMin.java @@ -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 - * @return min value + * @param array the input array + * @exception IllegalArgumentException input array is empty + * @return the mimum value stored in the input array */ public static int findMin(int[] array) { - int min = array[0]; - for (int i = 1; i < array.length; ++i) { - if (array[i] < min) { - min = array[i]; + if (array.length == 0) { + throw new IllegalArgumentException("array must be non-empty."); + } + int min = Integer.MAX_VALUE; + for (final var value : array) { + if (value < min) { + min = value; } } return min; diff --git a/src/test/java/com/thealgorithms/maths/FindMinTest.java b/src/test/java/com/thealgorithms/maths/FindMinTest.java index 48fcb277d..dc9835475 100644 --- a/src/test/java/com/thealgorithms/maths/FindMinTest.java +++ b/src/test/java/com/thealgorithms/maths/FindMinTest.java @@ -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; @@ -23,4 +24,17 @@ public class FindMinTest { public void test2() { 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[]{}) + ); + } }