Wednesday, February 3, 2016

To find second and first minimum element in an array

To find second and first minimum element in an array 

// Time Complexity : O(n) - Only 1 pass is required.
public class SecondMinimum {
      public static void main(String[] args) {

            int[] arr = new int[] { 34, 45, 21, 12, 54, 67, 15 };
            int first, second, arr_size = arr.length;

            /* There should be atleast two elements */
            if (arr_size < 2) {
                  System.out.println(" Invalid Input ");
                  return;
            }

            first = second = Integer.MAX_VALUE;
            for (int i = 0; i < arr_size; i++) {
                  /*If current element is smaller than first then update    both first and second*/
                  if (arr[i] < first) {
                        second = first;
                        first = arr[i];
                  }

                  /* If arr[i] is in between first and second then update second*/
                  else if (arr[i] < second && arr[i] != first)
                        second = arr[i];
            }
            if (second == Integer.MAX_VALUE)
                  System.out.println("There is no second" + "smallest element");
            else
                  System.out.println("The smallest element is " + first
                              + " and second Smallest" + " element is " + second);
      }
}

No comments:

Post a Comment