How to perform bubble sort in java

Bubble sort is one of the most interesting method of sorting an unsorted array in java.In bubble sort the value of first position is  compared with the value of position+1.

If we want to sort the array in ascending order then If the first value is greater than the value next to it than it swap the values.This process is continues till the array become sorted.

Code for performing bubble sort in java:-

          public class bubblesort {
       public static void main(String[] args) {
       int a[]={-5,-3,1,6,4,8,2,3,12,5};
       for(int i=0;i<=a.length-2;i++)
       {
           for(int j=0;j<=a.length-2;j++)
       {
          if(a[j]>a[j+1])
      {
         int temp=a[j];
        a[j]=a[j+1];
         a[j+1]=temp;

      }
    }
  }
     System.out.print(“The sorted array are as follows= “);
       for(int i=0;i<=a.length-1;i++)
     {
       System.out.print(a[i]+” “);
    }
     System.out.println();
    }

      } 

The output is:-

Leave a Reply