You are here: Home / Topics / Bubble sort example in java

Bubble sort example in java

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

// Program to SORT the Array elements using BUBBLE SORT

class  BubbleSort
{
public static void main( String args[ ] )
{
 int i, j, t;
 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 ] + "  " );
 }
 
 for( i=0 ; i<5-1 ; i++ )
 {
  for( j=0 ; j < (5-1-i) ; j++ )
  {
   if( a[ j ] > a[j+1] )
   {
    t = a[ j ];
    a[ j ] = a[j+1];
    a[j+1] = t;
   }
  }
 }
 
 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.