Selection Sort - Coder's point

Saturday, March 16, 2019

Selection Sort

 import java.util.*;  
 class selection_sort  
 {  
   void sort(int array[])  
   {  
    int i,j,small,temp,pos=0,k=0;  
    for( i=0;i<array.length;i++)  
    {  
      small=array[i];  
      pos=i;  
      for(j=i+1;j<array.length;j++)  
      {  
        if(array[j]<small)  
        {  
          small=array[j];  
          pos=j;  
         }  
       }  
       temp=array[pos];  
       array[pos]=array[i];  
       array[i]=temp;  
     }  
   }  
   public static void main()  
   {  
     selection_sort ob = new selection_sort();  
     Scanner in = new Scanner(System.in);  
     System.out.println("Enter the size of array ");  
     int n=in.nextInt();  
     int array[]=new int[n];  
      System.out.println("Enter the elements ");  
     for(int i=0;i<n;i++)  
     {  
       array[i]=in.nextInt();  
     }  
     ob.sort(array);  
     System.out.println("After selection sort :");  
     for(int i=0;i<array.length;i++)  
     {  
       System.out.print(" "+array[i]);  
     }  
     System.out.println();  
   }  
 }  
OUTPUT:
Enter the size of array 
5
Enter the elements 
12
34
56
87
1
After selection sort :
 1 12 34 56 87

No comments:

Post a Comment