public class BubbleSortAscending {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 3};
System.out.println("Before sorting:");
printArray(arr);
bubbleSortAscending(arr);
System.out.println("After sorting in ascending order:");
printArray(arr);
}
public static void bubbleSortAscending(int[] arr) {
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]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
Before sorting:5 2 8 1 3
After sorting in ascending order:
1 2 3 5 8 arr and initialize it with the values 5, 2, 8, 1, and 3. We then print the array before sorting using the printArray method.bubbleSortAscending method and pass the array as an argument. This method performs a bubble sort on the array in ascending order.printArray method.public class BubbleSortDescending {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 3};
System.out.println("Before sorting:");
printArray(arr);
bubbleSortDescending(arr);
System.out.println("After sorting in descending order:");
printArray(arr);
}
public static void bubbleSortDescending(int[] arr) {
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]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
Before sorting:5 2 8 1 3
After sorting in descending order:8 5 3 2 1