Home » Java » Bubble Sort Algorithm with full code – Java

Bubble Sort Algorithm with full code – Java

public class Sorts {

    public static void main(String[] args) {
        int[] arr1 = {9,14,3,2,43,11,58,22};    
        System.out.println("Before Bubble Sort");    
        for(int i: arr1){    
            System.out.print(i + " ");    
        }    
        System.out.println();    
            
        // sorting array using  bubble sort    
        bubbleSort(arr1);
        
        System.out.println("After bubble Sort");    
        for(int i: arr1){    
            System.out.print(i+" ");    
        } 
    }  
    
    static void bubbleSort(int[] arr) {  
        int n = arr.length;  
        int temp = 0;  
        for(int i=0; i < n; i++){  
            for(int j=1; j < (n-i); j++){  
                if(arr[j-1] > arr[j]){  
                    //swap elements  
                    temp = arr[j-1];  
                    arr[j-1] = arr[j];  
                    arr[j] = temp;  
                }  
            }  
        }  
    }  
}
Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*