Adsense 728 * 15

Search

Custom Search

Bubble Sort Program in Java

Write a Java program to implement a bubble sort algorithm. Given an unsorted array, we have to write a bubble sort program in Java.

Bubble sort program, algorithm and their time complexity

Time complexity of a sorting algorithms

Java programs

The average and worst case time complexity of bubble sort is O(n2)

Bubble Sort Program in Java


Java Program to Implement Bubble Sort


package bubblesort;

import java.util.*;


public class Bubblesort {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        int n, i, temp;
        
        Scanner in = new Scanner(System.in);
        
        System.out.println("Enter number of elements in an array");
        n  =  in.nextInt();
        
        int arr[] = new int[n];
        
        System.out.println("Enter values in an array");
        
        for(i = 0; i < n; i++) {
            arr[i] = in.nextInt();
        }
        
        //Bubble sort algorithm implementation
        for(i = 0; i < n-1; i++) {
            for(int j = 0; j < n-i-1; j++) {
                if (arr[j] > arr[j+1]) {
                    temp      = arr[j+1];
                    arr[j+1]  = arr[j];
                    arr[j]    = temp;
                }
            }
        }
        
        System.out.println("After sorting an array");
        
        for( i = 0; i < n; i++) {
            System.out.println(arr[i]);
        }
        
    }
    
}


Output -

Enter number of elements in an array  -  5

Enter values in an array
5
1
8
3
9
After sorting an array
1
3
5
8
9

No comments:

Post a Comment