Write a
recursive program to find greatest elements in array.
import java.util.Objects; public class MaximumFinder { public static int getMaximum(int arr[]) { Objects.nonNull(arr); if (arr.length < 0) return Integer.MIN_VALUE; return maximum(arr, 0); } private static int maximum(int arr[], int index) { if (index == arr.length - 1) return arr[index]; int val = maximum(arr, index + 1); if (val < arr[index]) return arr[index]; return val; } }
Following is
the junit test case for above program.
import static org.junit.Assert.assertEquals; import org.junit.Test; public class MaximumFinderTest { @Test public void test1() { int arr1[] = { 1, 2, 3, 4, 5 }; int arr2[] = { 5, 2, -2, 10, 5 }; int arr3[] = { 1 }; assertEquals(MaximumFinder.getMaximum(arr1), 5); assertEquals(MaximumFinder.getMaximum(arr2), 10); assertEquals(MaximumFinder.getMaximum(arr3), 1); } }
No comments:
Post a Comment