Bubble Sort - Coder's point

Saturday, March 16, 2019

Bubble Sort

 import java.util.*;  
 class bubble_sort  
 {    
   void sort(int num[])  
   {  
     int j;  
     boolean flag=true;  
     int temp;  
     while(flag)  
     {  
       flag=false;  
       for(j=0;j<num.length-1;j++)  
       {  
         if (num[j]>num[j+1])  
         {  
           temp=num[j+1];  
           num[j+1]=num[j];  
           num[j]=temp;  
           flag=true;  
         }  
       }  
     }  
   }  
   public static void main()  
   {  
     bubble_sort ob = new bubble_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 bubble 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 
112
34
56
178
45
After bubble sort :
 34 45 56 112 178

No comments:

Post a Comment