Bubble Sort Java Program

Bubble sort in java is the simplest sorting technique. In bubble sort algorithm each element is compared to next adjacent element, if the next element is smaller, then it will be swapped by previous element. Although this technique is simple but it is too slow as compared to other sorting techniques. Below I have shared the bubble sort java program. If you find anything missing or incorrect then please mention it in comment section. You can also ask your queries.

Bubble Sort Java Program

import java.util.Scanner;

class BubbleSort
{
 public static void main(String...s)
 {
  int a[]=new int[20],n,i,j,temp;

  Scanner sc=new Scanner(System.in);
  System.out.println("Enter how many elements:");
  n=sc.nextInt();

  System.out.println("nEnter elements of array:");
  
  for(i=0;i<n;++i)
   a[i]=sc.nextInt();

  for(i=1;i<n;++i)
   for(j=0;j<n-i;++j)
   {
    if(a[j]>a[j+1])
    {
     temp=a[j];
     a[j]=a[j+1];
     a[j+1]=temp;
    }
   }

  System.out.println("nArray after bubble sort:");

  for(i=0;i<n;++i)
   System.out.print(a[i]+" "); 
 }
}  

 

Bubble Sort Java Program

Leave a Comment

Your email address will not be published. Required fields are marked *