Given an array the task is to find the second smallest element present in the array.
Example: Consider an array with data {5, 1, 0, 9, 4}. The program should find the second smallest element from this array which is 1.
Java
import java.util.*;
public class SecondSmallestElement
{
public static void main(String args[])
{
int size=0,smin=0,temp=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter array size: ");
size=sc.nextInt();
int ar[]=new int[size];
System.out.println("Enter array elements:-");
for(int i=0;i<size;i++)
{
ar[i]=sc.nextInt();
}
smin=ar[0];
for(int i=0;i<size-1;i++)
{
for(int j=0;j<size-1-i;j++)
{
if(ar[j]>ar[j+1])
{
temp=ar[j];
ar[j]=ar[j+1];
ar[j+1]=temp;
}
}
smin=ar[1];
}
System.out.println("The second smallest element in the array is "+smin);
}
}Java