Write a Java Program to Perform Bubble Sort

By | 03.02.2017

Write a Java Program to Perform Bubble Sort


To perform bubble sort in Java Programming, you have to ask to the user to enter the array size then ask to enter the array elements, now start sorting the array elements using the bubble sort technique.

Following Java Program sort the array using the Bubble Sort technique :

 

SOURCE CODE ::

 

import java.util.Scanner;

public class BubbleSort {
    
//------------------Enter data Function---------------------------------
    
   static int [] enter_data()
    {
        int i,n;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter no. of elements u want to sort :");
        n=sc.nextInt();
        int a[]=new int[n];
        System.out.println("Enter elements--->");
        
        for(i=0;i<n;i++)
        {
            System.out.print((i+1)+" Element : ");
            a[i]=sc.nextInt();
        }
        return a;
    }

    //--------------------Bubble Sort Function-----------------------------
    
    static int [] bubblesort(int a[])
    {
        int i,j,temp,len;
        len=a.length;
        
        for(i=0;i<len;i++)
        {
            for(j=0;j<len-i-1;j++)
            {
                if(a[j]>a[j+1])
                {
                    temp=a[j];
                    a[j]=a[j+1];
                    a[j+1]=temp;
                }
            }
        }
        
        return a;
    }
    
    //-----------------Print array---------------------------------------
    
    static void printarray(int arr[])
    {
        int i,len;
        len=arr.length;
         System.out.println("\nAfter Sorting Elements are : ");
         for(i=0;i<len;i++)
        {
            System.out.println((i+1)+" Element : "+arr[i]);
        }
    }
    
    
    //-----------------------Main Function-------------------------------
    
    public static void main(String[] args) {
        
        int a[],b[];
        
        a=enter_data();
        
        b=bubblesort(a);
        
        printarray(b);
        
    }
    
}

 

OUTPUT ::

 

Enter no. of elements u want to sort :5
Enter elements--->
1 Element : 3
2 Element : 1
3 Element : 6
4 Element : 9
5 Element : 3

After Sorting Elements are : 
1 Element : 1
2 Element : 3
3 Element : 3
4 Element : 6
5 Element : 9

 

0 0 votes
Article Rating
Category: Arrays Programs Java Programming Tags:

About Tunde A

My name is Tunde Ajetomobi, a Tech Enthusiast and Growth Hacker. I enjoy creating helpful content that solves problem across different topics. Codezclub is my way of helping young aspiring programmers and students to hone their skills and find solutions on fundamental programming languages.

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments