Friday, April 15, 2011

Selection sort


import java.util.Scanner;
class SelectionSort
{
    static void Selection(int x[],int n)
    {
        int i,indx,j,large;
        for(i=n-1;i>0;i--)
        {
            large=x[0];
            indx=0;
            for(j=1;j<=i;j++)
                if(x[j]>large)
                {
                    large=x[j];
                    indx=j;
                }

            x[indx]=x[i];
            x[i]=large;
            for(int v=0;v<n;v++)
                System.out.print("\t"+x[v]);
            System.out.println();
        }
    }
   
    public static void main(String args[ ])
                {
                                int i,n=10;
        Scanner in = new Scanner(System.in);
        System.out.print("Enter how many numbers to be sorted : ");
        n = in.nextInt();
        int x[]=new int[n];
        System.out.println("Enter numbers");
        for(i=0;i<n;i++)
            x[i] = in.nextInt();
        Selection(x,n);
        System.out.println("\nSorted Elements are :");
        for(i=0;i<n;i++)
        System.out.print(x[i] + "  ");

    }
}





No comments:

Post a Comment