Question #223682

Given the following values,
10, 50, 30, 40, 20.
Define an array that will store the values
and use the bubble sort to display them in
descending order and in ascending order.

Results 'can' look like this:

Before Desc Asce
10 50 10
50 40 20
30 30 30
40 20 40
20 10 50

Expert's answer

public class Main{  
    static void bubble_sort(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]){  
                                 temp = arr[j-1];  
                                 arr[j-1] = arr[j];  
                                 arr[j] = temp;  
                         }  
                          
                 }  
         }  
  
    }  
    public static void main(String[] args) {  
                int array1[] ={10, 50, 30, 40, 20};  
                 
                System.out.println("Before Bubble Sort");  
                for(int i=0; i < array1.length; i++){  
                        System.out.print(array1[i] + " ");  
                }  
                System.out.println();  
                  
                bubble_sort(array1);  
                 
                System.out.println("After Bubble Sort");  
                for(int i=0; i < array1.length; i++){  
                        System.out.print(array1[i] + " ");  
                }  
   
        }  
}  
LATEST TUTORIALS
APPROVED BY CLIENTS