Answer to Question #231594 in Java | JSP | JSF for nothando

Question #231594

write 2 methods named descBubbleSort() and descInsertionSort() that take an array

of Strings as an argument and sort the string values in a descending order using

bubble sort and insertion sort respectively. 



1
Expert's answer
2021-08-31T17:35:56-0400
public class BubbleSort {
    
    

    public static void main(String args[]){
        BubbleSort bs=new BubbleSort();
        int array[]={34,45,2,41,9,14,9};
        
        bs.descBubbleSort(array);
        bs.descInsertionSort(array);;
    }
    
    public void descBubbleSort(int arr[]){
        System.out.println("Bubble sort by calling descBubbleSort function:");
         int temp=0;
        int n = arr.length;
        for(int i=0;i<n-1;i++){
            for(int j=0;j<(n-i)-1;j++){
                
                    if(arr[j]<arr[j+1]){
                        temp=arr[j];
                        arr[j]=arr[j+1];
                        arr[j+1]=temp;
                        }
            }
        }
        
        
            for (int i=0; i<n; ++i){
                System.out.print(arr[i] + " ");
            }
            System.out.println();
        
        
    }
    
    public void descInsertionSort(int arr[]){
        System.out.println("Insertion sort by calling descInsertionSort function:");
        
        int n=arr.length;
        for(int i=0;i<n;i++){
            int temp=arr[i];
            int j=i-1;
            while(j>=0 && arr[j]>temp){
                arr[j+1]=arr[j];
                j=j-1;
            }
            arr[j+1]=temp;
        }
        
        for (int i=(n-1); i>=0; --i){
            System.out.print(arr[i] + " ");
        }
        System.out.println();    
    }
    
}

Output:


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS