📘 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.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides 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