Write a program for Bubble Sort in Java

Bubble sort uses simple algorithm for sorting adjacent numbers with swapping each other by comparing both values one by one, which print order in the right manner. You can see the implemented code for Bubble Sort :

Code :
 public class BubbleSort {  
 public static void main(String args[])  
 {  
      int a[]={4,3,2,0,5,1};  
      System.out.println("Before Bubble Sort");  
      for(int i=0;i<a.length;i++)  
      {  
           System.out.print(a[i] + ",");  
      }  
      System.out.print("\n");  
      bubbleSort(a);  
      System.out.println("After Bubble Sort");  
      for(int i=0;i<a.length;i++)  
      {  
           System.out.print(a[i] + ",");  
      }  
 }  
 public static void bubbleSort(int a[])  
 {  
      int temp=0;  
      int n=a.length;  
      for(int i=0;i<n;i++)  
      {  
           for(int j=0;j<n-i-1;j++)  
           {  
                if(a[j]>a[j+1])  
                {  
                temp=a[j];  
                a[j]=a[j+1];  
                a[j+1]=temp;  
                }  
           }  
      }  
 }  
 }  
Output :
Before Bubble Sort
4,3,2,0,5,1,
After Bubble Sort
0,1,2,3,4,5,

No comments: