
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement Insertion Sort in Java
In this article, we will learn to implement insertion sort in Java. The insertion sort is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted. For example, the lower part of an array is maintained to be sorted. An element to be inserted in this sorted sub-list must find its appropriate place and then be inserted there. Hence the name, insertion sort.
The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list (in the same array).
Problem Statement
For a given array write a program in Java to implement insertion sort.
Input
array[] = {10, 20, 25, 63, 96, 57}
Output
10 20 25 57 63 96
Insertion Sort Algorithm
Step to implement the insertion sort algorithm ?
- If it is the first element, it is already sorted. return 1;
- Pick next element
- Compare with all elements in the sorted sub-list
- Shift all the elements in the sorted sub-list that is greater than the value to be sorted
- Insert for loop the value
- Repeat until the list is sorted
Pseudocode
Below is the pseudocode of the insertion sort algorithm ?
Algorithm: Insertion-Sort(A)
for j = 2 to A.length
key = A[j]
i = j - 1
while i > 0 and A[i] > key
A[i + 1] = A[i]
i = i -1
A[i + 1] = key
Java program to implement insertion sort
Below is the Java program to implement insertion sort ?
public class InsertionSort { public static void main(String args[]){ int array[] = {10, 20, 25, 63, 96, 57}; int size = array.length; for (int i=1 ;i< size; i++){ int val = array[i]; int pos = i; while(array[pos-1]>val && pos>0){ array[pos] = array[pos-1]; pos = pos-1; } array[pos] = val; } for (int i=0 ;i< size; i++){ System.out.print(" "+array[i]); } } }
Output
10 20 25 57 63 96
Time Complexity: O(N^2)
Auxiliary Space: O(1)
Code Explanation
The above Java program implements the insertion sort algorithm. It begins by initializing an array of integers and then determines the array's length. The main sorting logic occurs within a for loop that iterates over the array starting from the second element. For each element, the current value val is compared with the elements in the sorted portion of the array. If any element in the sorted part is greater than val, the loop shifts those elements to the right, making space for the insertion.
Finally, the val is placed in its correct position, ensuring the left side of the array remains sorted. After sorting, the program prints the sorted array elements in order.