Sunday 6 January 2013

PROGRAM FOR SELECTION SORT IN JAVA


import java.io.*;

class Selection

{

        public static void main ( String args[] )

        throws IOException

        {

                BufferedReader br = new BufferedReader ( new InputStreamReader ( System.in ) );

                System.out.print("\n\nEnter size of array : ");

                int n = Integer.parseInt ( br.readLine() );

                int a[] = new int[n];

                System.out.println("\n\nEnter array elements -\n");

                for ( int i=0 ; i<n ; i++ )

                {

                        System.out.print("\na[" + i + "] = ");        

                        a[i] = Integer.parseInt ( br.readLine() );

                }

                for ( int i=0 ; i<n-1 ; i++ )

                {

                        int ind = i;

                        int min = a[i];

                        for ( int j=i ; j<n ; j++ )

                        {

                                if ( min > a[j] )

                                {

                                        ind = j;

                                        min = a[j];

                                }

                        }

                        a[ind] = a[i];

                        a[i] = min;

                }

                System.out.print("\n\nSorted array  :  ");

                for ( int i=0 ; i<n ; i++ )

                        System.out.print(a[i] + "  ");

                System.out.println("\n");

        }

}

No comments: