Bubble sort program in Java

Bubble sort  in Java


Bubble sort in Java

Bubble sort
is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted. It compare each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. The algorithm for bubble sort requires a pair of nested loops. The outer loop must iterate once for each element in the data set (of size n) while the inner loop iterates n times the first time it is entered, n-1 times the second, and so on.  Bubble sort belongs to O(n2) sorting algorithms, which makes it quite inefficient for sorting large data volumes. Bubble sort is stable and adaptive.

First Version
import java.util.*;
public class BubbleSort
{
    public static void main(String args[])
    {
        int n[]=new int[5];
        int i, j, t;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter Elements in Array");
        for(i=0; i<5; i++)
        {
            n[i]=sc.nextInt();
        }
        System.out.println("Before Sorted Order");
        for(i=0;i<5;i++)
        {
            System.out.print(n[i] + " ");
        }
        System.out.println();
        for(i=0;i<4;i++)
        {
            for(j=0;j<4-i;j++)
            {
                if(n[j]>n[j+1])
                {
                    t=n[j];
                    n[j]=n[j+1];
                    n[j+1]=t;
                }
            }
        }
        System.out.println("Sorted Order");
        for(i=0;i<5;i++)
        {
            System.out.print(n[i] + " ");
        }
    }
}



Process defines pictorially 

second version
public class BubbleSortProject
{
        
        int n[]={8,18,20,6,1,4,19,16,15,3};
        int l,i,j,t;
        
        void Process()
        {
            l=n.length;
            for(i=0;i<l;i++)
            {
                System.out.print(n[i]+" ");
            }
            System.out.println();
        }
        void BubbleSort()
        {
            l=n.length;
            for(i=0;i<l-1;i++)
            {
                for(j=0;j<(l-1)-i;j++)
                {
                    if(n[j]<n[j+1])
                    {
                        t=n[j];
                        n[j]=n[j+1];
                        n[j+1]=t;
                    }
                }
            }
        }
        
        public static void main(String arg[])
        {
            BubbleSortProject ob=new BubbleSortProject();
            System.out.println("Before Sort");
            ob.Process();
            ob.BubbleSort();
            System.out.println("After Sort");
            ob.Process();
        }

}

Output:
Before Sort
8 18 20 6 1 4 19 16 15 3 
After Sort

20 19 18 16 15 8 6 4 3 1 



SHARE THIS
Previous Post
Next Post