find the second smallest number in an array in java



Program

public class SecondSmallest 
{
public static void main(String[] args)
{
int[] a = {-5, -4, 0, 2, 10, 30, -3};
int smallest = 0;
int secondSmallest = 0;
for (int i = 0; i < a.length; i++)
{
if(a[i]==smallest)
{
secondSmallest=smallest;
}
else if (a[i] < smallest)
{
secondSmallest = smallest;
smallest = a[i];
}
else if (a[i] < secondSmallest)
{
secondSmallest = a[i];
}

}
System.out.println(secondSmallest);
}
}



Output

-4

Related example

        Java program to find largest number in an array
        Java program to find second largest number in an array
        Java program to find largest and smallest number in an array
        Java program to find largest and second largest number in an array
        Java program to find second smallest number in an array
        Java program to find index of max value in array java
        Java program to find index of smallest element in array java


Related Post

Comments

Rodney
         How do we find the second smallest in multiple row values
Rodney
         I have a database with six columns. Name,score1,score2,score3,score4,score5. Each student has a record with all score columns filled. If James had score1=40,score2=70,score3=36,score4=60,score5=50. How do I write an sql query to select 40 as the second smallest score value.
Birendra
         This program will not work if the smallest number is in first position..if its like that then it will print that no. only that is first position no.

©candidjava.com