DWQA Ask QuestionCategory: JavaJava_Q: Bubble Sort Array
admin Staff asked 7 years ago

By using the bubble sort algorithm, write a Java program to sort an integer array of 10 elements in ascending.

 

Modify the above java code in exercise 1 to sort the array in descending order.

1 Answers
Kulkarni Arundhati answered 7 years ago
Start your code here
public class BubbleSort {
static void bubble(int[] a){
int b=a.length;
int temp=0;
for(int i=0;i<b;i++){
for(int j=1; j<(b-i);j++){
if(a[j-1]>a[j]){
//swap the element
temp=a[j-1];
a[j-1]= a[j];
a[j]=temp;
}
}
}
}

public static void main(String[] args) {
// TODO Auto-generated method stub
int a [] = {3,7,1,22,34,99,320,5};
System.out.println("Array before bubble sort");
for(int i=0; i<a.length; i++){
System.out.println(a[i] + "\t");
}
System.out.println();
bubble(a);//bubble sort
System.out.println("Array after bubble sort");
for(int i=0;i<a.length;i++){
System.out.println(a[i] + "\t");
}
}

}