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.
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:
Comments
Leave a comment