Sunday, 23 August 2015

Recursive function to find minimum element in array

Write a recursive function that finds and returns the minimum element in an array.
import java.util.Objects;

public class FindMin {

 public static int findmin(int a[]) {
  Objects.nonNull(a);
  if (a.length == 0)
   throw new IllegalArgumentException("Input is empty");

  return findMinimum(a, 0);
 }

 private static int findMinimum(int a[], int index) {
  if (index == a.length - 1)
   return a[index];

  int val = findMinimum(a, index + 1);
  if (a[index] < val)
   return a[index];
  else
   return val;
 }
}


Following is the junit test.
import static org.junit.Assert.*;

import org.junit.Test;

public class FindMinTest {

 @Test
 public void test1(){
  int arr1[] = {1, 2, 3, 4, 5};
  int arr2[] = {5, 2, -2, 10, 5};
  
  assertEquals(FindMin.findmin(arr1),1);
  assertEquals(FindMin.findmin(arr2),-2);
 }
}


No comments:

Post a Comment