📘 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 a sorting algorithm that places an unsorted element at its suitable place in each iteration. Insertion sort works similarly as we sort cards in our hands in a card game.
In this blog post, we will deep dive into the mechanism of Insertion Sort, followed by its implementation in Java to sort an array in ascending order.
Java Program for Insertion Sort in Ascending Order:
public class InsertionSortAscending {
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 ascending order:");
for (int num : numbers) {
System.out.print(num + " ");
}
}
/**
* Sort an array using the insertion sort algorithm.
*
* @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 ascending order:
-22 -15 1 7 20 35 55
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