Algoritham and Program for Bubble Sort

Algorithm for Bubble Sort:

v  Bubble sort is  used to arrange the data in a particular order.The order may be either ascending or descending order.
v  An array contains a[0] to a[n – 1] elements.
      v  Bubble sort algorithm works as follows.

Step 1: compare a[0] and a[1] and arrange in ascending order i.e, a[0]
           
 Compare a[1] and a[2] and arrange in ascending order i.e., a[1]
   .................
   .................
    ................                                            
  Compare a[n–2] and a[n–1] and arrange in ascending order i.e., a[n – 2]
v  Finally a[n – 1] contains the largest element .
v  Step -1 involves (n – 1) comparisons.

Step -2: repeat step – 1 with one less comparison i.e., now we stop after we compare and arrange a[n – 3] and a[n- 2].
................
................

Step(n – 1): compare a[0] and a[1] and arrange in particular order i.e., a[0]

Time Complexity: Time complexity or efficiency of bubble sort algorithm is 0[n2]
v  Time complexity or efficiency of an algorithm is calculated based on two conditions.
i)             Number of iterations
ii)            Number of comparisons.



Bubble Sort Program:


class Bsort
{
  public static void main(String args[ ])throws IOException
{
   int x[ ]={10,8,7,5,3};
   int n=x.length;
   int i,j,temp;
   System.out.println(“before sorting elements are”);
  for(i=o;i<=n;i++)
  {
     System.out.println(“x[“+i+”]=”x[ i ] );
   }
 for(i=1;i
  {
    for(j=0;j
   {
      if(a[j]>a[j+1])
     {
      temp=a[j];
      a[j]=a[j+1];
      a[j+1]=temp;
     }
  }
}
  System.out.println(“after sorting the elementsare”);
  for(i=0;i
  {
    System.out.println(“x[“+i+”]=”+x[i]);
   }
  }
}


Related

Data Structures 4430289842761818748

Post a Comment

emo-but-icon

item