Thursday, 29 November 2012

Write a Java Program to find second smallest element of an array.


package Small2;
public class small2 {

 
    public static void main(String[] args) {
        int []A = {10,2,8,15,-2};
        SecondSmall slg = new SecondSmall();
        int y = slg.findsecondsmall(A);
        System.out.println("Second Smallest element of Array A is "+ y);
     
        int []B = {10,15,30,5,7};
        y = slg.findsecondsmall(B);
        System.out.println("Second Smallest element of Array B is "+ y);
     
        int []C = {13,74,29,30,31,73,62,22};
        y = slg.findsecondsmall(C);
        System.out.println("Second Smallest element of Array C is "+ y);
     
        int []D = {1,2,3,4,5,6,7};
        y = slg.findsecondsmall(D);
        System.out.println("Second Smallest element of Array D is "+ y);
     
        int []E = {7,6,5,4,3,2,1};
        y = slg.findsecondsmall(E);
        System.out.println("Second Smallest element of Array E is "+ y);
     
        int []F = {7,6,5,4,3,2,1,-1,-2,-3,-4,-5,-6,-7};
        y = slg.findsecondsmall(F);
        System.out.println("Second Smallest element of Array F is "+ y);
    }
}


class SecondSmall
{
    int findsecondsmall(int A[])
    {
        int first1 = A[0];
        int first2 = A[1];
        int i = 1;
        for(;i<A.length;i++)
        {
            if(A[i]<first1)
            {
                first2 = first1 ;
                first1 = A[i];
            }
         
            else if(A[i]<first2)
            {
                first2 = A[i];
            }
        }
        return first2;
     
    }
}

0 comments

 
© 2011-2012 ProgrammingBlue
Posts RSS Comments RSS
Back to top