📘 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
Insertion sort is an elementary and intuitive sorting algorithm that's efficient for relatively small datasets. It's analogous to the process of sorting playing cards in one's hands. While ascending order is more common, you might sometimes need to sort data in descending order. In this article, we'll walk you through the mechanism of Insertion Sort and how to use it to sort an array in descending order in Java.
Java Program for Insertion Sort in Descending Order
public class InsertionSortDescending {
public static void main(String[] args) {
// Sample array of numbers to be sorted
int[] numbers = {20, 35, -15, 7, 55, 1, -22};
// Sort the array using Insertion Sort
insertionSort(numbers);
// Display the sorted array
System.out.println("Sorted array in descending order:");
for (int num : numbers) {
System.out.print(num + " ");
}
}
/**
* Sort an array using the insertion sort algorithm in descending order.
*
* @param arr The array to be sorted.
*/
public static void insertionSort(int[] arr) {
for (int firstUnsortedIndex = 1; firstUnsortedIndex < arr.length; firstUnsortedIndex++) {
int newElement = arr[firstUnsortedIndex];
int i;
// Compare the new element to elements in the sorted section of the array
for (i = firstUnsortedIndex; i > 0 && arr[i - 1] < newElement; i--) {
arr[i] = arr[i - 1];
}
// Insert the newElement into its appropriate position
arr[i] = newElement;
}
}
}
Output:
Sorted array in descending order:
55 35 20 7 1 -15 -22
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