Selection Sort

 

// 4. Selection Sort

import java.io.*;

import java.util.*;

 

class SelectionSort

{

     public static void main(String [] as) throws IOException

     {

          Scanner sc = new Scanner(System.in);

          int i, j, pos, arrlen, tmp;

         

          System.out.print("Enter array length : ");

          arrlen = sc.nextInt();

         

 

          System.out.println("Enter array elements : ");

          int arr[] = new int[arrlen];

          for(i=0;i<arrlen;i++)

              arr[i]=sc.nextInt();

         

          // Sorting

          for(i=0;i<arrlen-1;i++)

          {

              pos=i;

              for(j=i+1;j<arrlen;j++)

              {

                   if(arr[j]<arr[pos])

                        pos=j;

              }

              tmp=arr[pos];

              arr[pos] = arr[i];

              arr[i] = tmp;

          }

             

          System.out.print("Sorted array : ");

          for(i=0;i<arrlen;i++)

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

         

     }

}

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu