Bubble Sort in Java Program

Bubble Sort is simplest sorting algorithm. In Bubble Sort, array is traversed from first element to last element. Here, current element is compared with the next element. If current element is greater than the next element, it is swapped.
This algorithm is not suitable for large data sets as its average and worst case complexity are of Ο(n2) where n is the number of items.

Lets see Bubble Sort Program in Java.

public class BubbleSortExample {  
    
    static void BubbleSort(int arr[]){
        
        int n=arr.length;
        int temp;
        
        for(int i=0;i<n;i++){
            for(int j=1;j<(n-i);j++){
                if(arr[j-1]>arr[j]){
                    temp = arr[j-1];  
                    arr[j-1] = arr[j];  
                    arr[j] = temp;  
                }
            }
        }
        
    }
     
    public static void main(String[] args) {  
        
        int arr[] ={3,60,35,2,45,320,5};  
                 
        System.out.println("Array before Bubble Sort:");
                
        for(int i=0;i<arr.length;i++){
            System.out.print("  "+arr[i]);
        }
                
        BubbleSort(arr);
                
        System.out.println("Array after Bubble Sort:");
                
        for(int i=0;i<arr.length;i++){
            System.out.print("  "+arr[i]);
        }
   
    }  
    
}  

YOU MAY BE INTERESTED:

Comments