There are different sorting algorithms are available like selection sort, insertion sort etc. In this article we learn about one of them sorting algorithm. Also working of this sorting algorithm and example of this sorting algorithm.

Insertion sorting algorithm is the simplest sorting algorithm as compare to other sorting algorithms. Insertion sorting is a simple sorting algorithm that works the way we sort playing cards in our hands.


Step 1 − If it is the first element, it is already sorted.  
         return 1;
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted

Program: Java program for implementation of Insertion Sort algorithm

In the following program we pass the integer array of numbers for sorting. Before sorting array int arr looks like {12, 11, 13, 5, 6} and after performing insertion sorting array of integers looks like {5, 6, 11, 12, 13}.

class InsertionSort
/Function to sort array using insertion sort/
void sort(int arr[])
int n = arr.length;
for (int i=1; i<n; ++i)
int key = arr[i];
int j = i-1;
while (j>=0 && arr[j] > key)
arr[j+1] = arr[j]; 
j = j-1; 
arr[j+1] = key; 
static void printArray(int arr[])
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
public static void main(String args[])
int arr[] = {12, 11, 13, 5, 6};
InsertionSort ob = new

Output: displays the sorted values in an array by ascending order.

5 6 11 12 13
Insertion Sort

In the above programs output we see that the values are sorted. Here, in this article we sort the arrays by ascending order we can also try this sorting for descending order.i.e increasing order or decreasing order.

Other than the insertion sorting we write the articles for other sorting algorithms which are available in programming like bubble sort, merge sort. If you want to learn about them then see below articles. Learn about merge sort see this article Merge Sort. If you want to learn bubble sort, quick sort, selection sort then see this article bubble SortQuick sortSelection sort.

I hope you would like this article of sorting. If you face any difficulty or you are having any query then comment me I will definitely try to respond you…

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top