📘 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
In this blog post, we'll explore the mechanism of sorting an array in descending order using Selection Sort in Java.
Java Program for Selection Sort in Descending Order
public class SelectionSortDescending {
public static void main(String[] args) {
// Initialize a sample array of numbers
int[] numbers = {64, 34, 25, 12, 22, 11, 90};
// Sort the array using Selection Sort
selectionSort(numbers);
// Display the sorted array
System.out.println("Sorted array in descending order:");
for (int num : numbers) {
System.out.print(num + " ");
}
}
/**
* Perform selection sort on the given array in descending order.
*
* @param arr The array to be sorted.
*/
public static void selectionSort(int[] arr) {
int n = arr.length;
// One by one move the boundary of the unsorted sub-array
for (int i = 0; i < n - 1; i++) {
// Find the maximum element in the unsorted array
int max_idx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] > arr[max_idx]) {
max_idx = j;
}
}
// Swap the found maximum element with the first element of the sub-array
int temp = arr[max_idx];
arr[max_idx] = arr[i];
arr[i] = temp;
}
}
}
Output:
Sorted array in descending order:
90 64 34 25 22 12 11
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