- Given an array of integers in java.
- Print second smallest element in an array (in single iteration).
- We have already discussed to find out second largest element in an array of integers.
Example – find second smallest element in an array of integers (java).
Example 1:
- Given an input array {2, 4, 6, 8, 10, 12}.
- Smallest element in an array is 2 and second smallest element in an array is 4.
Example 2:
- Given an input array {5, 3, 4, 1, 2}.
- Smallest element in an array is 1 and second smallest element in an array is 2.
Example 3:
- Given an input array {16, 41, 41, 9, 41, 7}.
- Smallest element in an array is 7 and second smallest element in an array is 9.
Program – second smallest element in an array of integers (java/ example).
1.) SecondSmallestElement class:
- SecondSmallestElement class is responsible for finding the second smallest element in an array,
- printSecondSmallestElement method will print second smallest element.
package org.learn;
import java.util.Arrays;
public class SecondSmallestElement {
public static void main(String[] args) {
int[] inputArray = {2, 4, 6, 8, 10, 12};
printSecondSmallestElement(inputArray);
System.out.println();
inputArray = new int[]{5, 3, 4, 1, 2};
printSecondSmallestElement(inputArray);
System.out.println();
inputArray = new int[]{16, 41, 41, 9, 41, 7};
printSecondSmallestElement(inputArray);
}
private static void printSecondSmallestElement(int[] inputArray) {
int firstSmallest = inputArray[0];
int secondSmallest = Integer.MAX_VALUE;
for (int index = 1; index < inputArray.length; index++) {
int currentElement = inputArray[index];
if(firstSmallest > currentElement) {
secondSmallest = firstSmallest;
firstSmallest = currentElement;
} else if(secondSmallest > currentElement && firstSmallest < currentElement) {
secondSmallest = currentElement;
}
}
String array = Arrays.toString(inputArray);
if(secondSmallest != Integer.MIN_VALUE) {
System.out.printf("Second Smallest element in %s is : %d",array,secondSmallest);
} else {
System.out.printf("There is not second Smallest element in array %s ",array);
}
}
}
Output – second largest element in an array of integers in java
Second Smallest element in [2, 4, 6, 8, 10, 12] is : 4
Second Smallest element in [5, 3, 4, 1, 2] is : 2
Second Smallest element in [16, 41, 41, 9, 41, 7] is : 9