Find Second Smallest Element In An Array | Java Programs

Output:

*** Second Smallest Number In Array ***

Original Array is: [-10, 42, 90, 21, 72, -3]
Second smallest number is : -3

Click Here For Java Online Compiler

Solution:

import java.util.Arrays;

public class SecondSmallestInArray {

    public static void main(String[] args) {

        int[] array = {-10, 42, 90, 21, 72, -3};
        System.out.println("*** Second Smallest Number In Array ***" + "\n");
        System.out.println("Original Array is: " + Arrays.toString(array));
        int min = Integer.MAX_VALUE;
        int secondMin = Integer.MAX_VALUE;
        for (int i = 0; i < array.length; i++) {
            if (array[i] == min) {
                secondMin = min;
            } else if (array[i] < min) {
                secondMin = min;
                min = array[i];
            } else if (array[i] < secondMin) {
                secondMin = array[i];
            }
        }
        System.out.println("Second smallest number is : " + secondMin);
    }
}
Share This :

Related Post



sentiment_satisfied Emoticon