You are here: Home / Topics / Selection sort example in Java

Selection sort example in Java

Filed under: Java on 2023-08-23 06:46:58

// Program to SORT the Array elements using SELECTION SORT

class  SelectionSort
{
public static void main( String args[ ] )
{
 int  i, j;
 int  a[ ] = { 40, 20, 50, 10, 30 };
 
 System.out.print( "\n Unorted Numbers are = " );
 for( i=0 ; i<5 ; i++ )
 {
  System.out.print( a[ i ] + "  " );
 }

 int  small, pos, tmp;
 for( i=0 ; i<5 ; i++ )
 {
  small = a[ i ];
  pos = i;
  for( j=i+1 ; j<5 ; j++ )
  {
   if( a[ j ] < small )
   {
    small = a[ j ];
    pos = j;
   }
  }
  tmp = a[ i ];
  a[ i ] = a[pos];
  a[pos] = tmp;
 }

 System.out.print( "\n Sorted Numbers are  = " );
 for( i=0 ; i<5 ; i++ )
 {
  System.out.print( a[ i ] + "  " );
 }
}
}


Output:

Unorted Numbers  are =  40  20  50  10  30 
Sorted Numbers  are  =  10  20  30  40  50

About Author:
J
Java     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.