Bubble Sort

Bubble Sort

Write a program to sort an array using Bubble Sort technique. In this technique, adjoining elements are compared and smaller/greater elements are shifted to the right depending on the type of sort.

import java.util.*;

class BubbleSort{

 public static void main(String args[])throws InputMismatchException{

   Scanner scan = new Scanner(System.in);

    int n,i,t, limit;
    boolean flag;

    System.out.println("Enter the number of elements : ");
    n = scan.nextInt();

   int a[] = new int[n]; //declare array 

    System.out.println("Enter " + n + " elements.");

    for(i = 0; i < n; i++) 
      a[i] = scan.nextInt();

    limit = n;

    //sort the array in ascending order
        flag = false;

         for(i = 0; i < limit-1; i++){

        if(a[i] > a[i+1]){

        t = a[i];

        a[i] = a[i+1];

        a[i+1] = t;     

        flag = true;

        }//end of if

      }//end of inner loop

         limit = limit - 1;


    //display the sorted array

    for(i = 0; i < n; i++){

        System.out.println(a[i] + " ");

    }//end of loop

   }//end of main
}//end of class   

Have something to say? Log in to comment on this post.