Thursday 13 August 2015

Find smallest and second smallest element in array

Suppose arr[] = {2, 3, 15, 23, 12, 13, 19, -10, 100}


First smallest element is -10 and second smallest element is 2.
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ArrayUtil {

 public static List<Integer> getSmallestElements(int arr[]) {
  Objects.nonNull(arr);

  List<Integer> myList = new ArrayList<>();

  if (arr.length < 2)
   return myList;

  int firstMin = arr[0];
  int secondMin = arr[1];

  if (firstMin > secondMin) {
   int temp = firstMin;
   firstMin = secondMin;
   secondMin = temp;
  }

  for (int i = 2; i < arr.length; i++) {
   if (arr[i] < secondMin) {
    if (arr[i] < firstMin) {
     secondMin = firstMin;
     firstMin = arr[i];
     continue;
    }
    secondMin = arr[i];
   }
  }

  myList.add(firstMin);
  myList.add(secondMin);
  return myList;
 }
}


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

import java.util.List;

import org.junit.Test;

public class ArrayUtilTest {

 @Test
 public void test1() {
  int arr1[] = { 2, 3, 15, 23, 12, 13, 19, -10, 100 };
  int arr2[] = { -10, -100 };

  List<Integer> expected1 = ArrayUtil.getSmallestElements(arr1);
  List<Integer> expected2 = ArrayUtil.getSmallestElements(arr2);

  assertEquals(expected1.get(0), new Integer(-10));
  assertEquals(expected1.get(1), new Integer(2));
  assertEquals(expected2.get(0), new Integer(-100));
  assertEquals(expected2.get(1), new Integer(-10));
 }

}



No comments:

Post a Comment