📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Bubble Sort is a simple and intuitive sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The procedure is repeated until no more swaps are required, which means the list is sorted. Although it's not the most efficient sorting algorithm in the world, its simplicity and ease of understanding make it a popular choice among beginners.
Java Program for Bubble Sort in Descending Order
public class BubbleSortDescending {
public static void main(String[] args) {
// Define a sample array of numbers
int[] numbers = {34, 12, 56, 78, 33};
// Sort the array using bubble sort in descending order
bubbleSortDescending(numbers);
// Display the sorted array
System.out.println("Sorted array in descending order:");
for (int num : numbers) {
System.out.print(num + " ");
}
}
/**
* Sorts an array of integers in descending order using Bubble Sort.
*
* @param arr The array to be sorted.
*/
public static void bubbleSortDescending(int[] arr) {
int n = arr.length; // Determine the length of the array
// Outer loop for the number of passes
for (int i = 0; i < n - 1; i++) {
// Flag to track if any swapping occurred during this pass
boolean swapped = false;
// Inner loop to compare and potentially swap adjacent elements
for (int j = 0; j < n - i - 1; j++) {
// If the current element is less than the next element (for descending order)
if (arr[j] < arr[j + 1]) {
// Swap the two elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
// Set the swapped flag to true since a swap has occurred
swapped = true;
}
}
// If no elements were swapped during this pass, the array is already sorted
if (!swapped) break;
}
}
}
Output:
Sorted array in descending order:
78 56 34 33 12
Step by Step Explanation
Related Java Programs on Sorting Algorithms
- Bubble Sort in Ascending Order in Java
- Bubble Sort in Descending Order in Java
- Selection Sort in Ascending Order in Java
- Selection Sort in Descending Order in Java
- Insertion Sort in Ascending Order in Java
- Insertion Sort in Descending Order in Java
- Merge Sort in Ascending Order in Java
- Merge Sort in Descending Order in Java
- Quick Sort in Ascending Order in Java
- Quick Sort in Descending Order in Java
Comments
Post a Comment
Leave Comment