by Dinesh Thakur Category: array

Algorithm for Bubble Sort:

step 1: read num

step 2: create an integer array a[] of size num

step 3: set flag =1

step 4: initialize i=0

step 5: repeat through step-11 while (i <n) and flag=l

step 6: Reset flag=0

step 7: Initialize j=0

step 8: repeat through step-10while (j<n-i-1)

step 9: compare a[j] and a [j+ 1]

if (a [jj>a [j+ 1j) then set the flag= 1 and interchange a[j] and a [j+ 1]

step 10: increment the value of 'j' as j=j+ 1

step 11: increment the value of 'i' as i=i+1

step 12: Exit

Here is the Java Example for Bubble Sort:

import java.util.Scanner;

public class BubbleSort
{
            public static void main(String args[])
      {
             int i,j,t,d;
             Scanner s=new Scanner(System.in);
             System.out.println("Enter The size of Array");
             d=s.nextInt();
             int a[]=new int[15];
             System.out.println("\nEnter the Elements Are");
             for(i=1;i<=d;i++)
                {
                   a[i]=s.nextInt();
                }
                   System.out.print("\nElements Are\n");
             for(i=1;i<=d;i++)
                {
                   System.out.print(a[i]+"\t");
                }
             for(i=1;i<=d;i++)
                {
             for(j=1;j<(d-1);j++)
                {
                    if(a[j]<a[j+1])
                     {
                        t=a[j];
                        a[j]=a[j+1];
                        a [j+1] =t ;
                     }
                }
          }
     System.out.println("\nAfter Bubble Sort Is:-\n");
            for(i=1;i<=d;i++)
               {
                  System.out.print(a[i ]+"\t") ;
               }
      }
}

Bubble Sort in Java





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles