×

Insertion sort

Insertion sort is a simple sorting technique. It is best suited for small data sets, but it does not suitable for large data sets. In this technique, we pick an element and insert it in its appropriate place. Insertion sort is not a fast sorting algorithm because it uses the nested loops to shift the elements in their place. But this is a better sorting technique than bubble sort and selection sort because the complexity of insertion sort is less than both.

If you have n elements in the array, you will need (n-1) pass to sort it.

Complexity table of Insertion sort

ComplexityBest caseAverage caseWorst case
TimeO(n)O(n2)O(n2)
Space  O(1)

Insertion sort algorithm

Insertion_sort(A)
 {   
Repeat for i = 2 to the length of A
      {          
 item = A[i]       
    j = i – 1           
Repeat while (j>0 and A[j] > item)  
               
{                   
 A[j+1] = A[j]                  
  j = j – 1         
        } // end of while loop        
  A[j+1] = item  
    } // end of for loop 
} // end of the insertion loop  

Insertion sort example

Suppose you have the following array, which you have to sort.

1186192

In insertion sort, the first two elements are compared.

There are 6 elements in this array, so you will need 5 iterations to sort it.

Iteration 1: Since 8 is smaller than 11, it will change its place among themselves.       
  8 11 6 1 9 2
Iteration 2: Now, you will compare the next two elements (11 and 6). Since 6 is smaller than 11, it will change its place among themselves. After this, 8 and 6 will compare, 6 is smaller than 8, so it will change its place among themselves.
6 8 11 1 9 2
Iteration 3: Now, you will compare 11 and 1. Since 1 is smaller than 11, it will change its place among themselves. After this, 8 and 1 will compare, 1 is smaller than 8, so it will change its place among themselves.
 1 6 8 11 9 2
Iteration 4: Now, you will compare 11 and 9. Since 9 is smaller than 11, it will change its place among themselves.   
  1 6 8 9 11 2
Iteration 5: Now, you will compare 11 and 2. Since 2 is smaller than 11, it will change its place among themselves. After this, 9 and 2 will compare, 2 is smaller than 9, so it will change its place among themselves.  
1 2 6 8 9 11  

Insertion sort program in C language:

#include<stdio.h>
   void main ()
   {      
int i, j, k, temp;       
int a[6] = { 11, 8, 6, 1, 9, 2};       
 printf("\n Insertion sort  \n");      
 for(k=1; k<6; k++)       
 {         
  temp = a[k];         
  j= k-1;           
while(j>=0 && temp <= a[j])          
 {              
 a[j+1] = a[j];               
 j = j-1;           
}           
a[j+1] = temp;      
 }      
 for(i=0;i<6;i++)      
 {           
printf("\n%d\n",a[i]);  
     } 
  }    

Output

Insertion sort
1 
2 
6 
8 
9 
11

Insertion sort program in java language:

public class InsertionSort
 {   
public static void main(String[] args) 
{       
int[] a = {11, 8, 6, 1, 9, 2};
       
for(int k=1; k<10; k++)
       {         
 int temp = a[k];
          
 int j= k-1;          
while(j>=0 && temp <= a[j])          
 {              
 a[j+1] = a[j];               
 j = j-1;           
}           
a[j+1] = temp;
       }       
System.out.println("Insertion sort ");
       for(int i=0;i<10;i++)
       {         
 System.out.println(a[i]);  
  } 
  } 
  }    

Output

Insertion sort
1 
2 
6 
8 
9 
11

Related Topics

A Full Binary Tree with n Nodes

Implementation // Writing the implementation of the above approach in C++ #include <bits/stdc++.h> using namespace std; // We are creating a class that will create a node and its left and right children.  struct __nod...

12 minutes read.

Priority Queue in Data Structure

Priority Queue A priority queue is a special kind of queue, in priority queue we give some priority to an element and according to this priority an element can be served...

3 minutes read.

What Is Graph Data Structure

A graph is generally a set of vertices and edges or border that is mainly used to join these vertices. A graph is basically pictured as a cyclic tree in...

7 minutes read.

Does Overloading Work with Inheritance

This is a question that occasionally comes to many programmers. Who are curious to know more now has a complete explanation and a solution through this tutorial! Inheritance: The functions of...

3 minutes read.

Detect and Remove Loop in a Linked List

Create a function called detectAndRemovetheLoop() that verifies whether a given Linked List has a loop, eliminates the loop if it does, and returns true if it does. It returns false...

6 minutes read.

What is the B+ Tree in Data Structures?

We all know that the B+ tree in data structures is nothing but just an extended version of the B tree. It allows the smooth working of all the operations...

7 minutes read.

Spanning Tree

Spanning Tree: The spanning tree is a subset of the graph. It is a non-cyclic graph. If any node in the spanning tree is truncated, the entire graph fails. There are...

10 minutes read.

AVL Tree

AVL Tree AVL Tree is referred to as self-balanced or height-balanced binary search tree where the difference between heights of its left subtree and right subtree (Balance Factor) can't more than...

25 minutes read.

Boruvkas algorithm

This algorithm is used for finding minimum spanning tree from a weighted graph. Like prim’s and kruskal’s algorithm it is also a greedy algorithm. Note:What is the minimum spanning tree?We know...

4 minutes read.

Delete the Middle element of the Linked List in C

Delete the Middle element of the Linked List in C This article has given a singly linked list and will delete the middle element of the given linked list. Example:  The given...

3 minutes read.

Binary search tree traversal in-order pre-order post-order examples

A binary search tree is a type of non-linear tree in which the tree contains at least two nods. It is called binary because of its nature that states bi...

8 minutes read.

What Is Dfs Algorithm in Data Structures

DFS stands for Depth First Search. Generally, it is a repetitive or decidable type of algorithm which is basically used in identifying all the vertices or nodes of a graph...

5 minutes read.

What is a Threaded Binary Tree?

When we consider those binary trees that are interlinked with each other, we do come across the fact that the fields present in there do consist of NULL values that...

3 minutes read.

Merge two sorted linked lists

Merge two sorted linked lists In this article, we are going to learn how to merge two linked lists. Here we have given two linked lists that are sorted in increasing...

7 minutes read.

Deletion in B+ Tree

Make a search for the leaf node that containing the key value by taking the value in a key value. If the required key value is found, then it will remove...

6 minutes read.

Applications of Different Linked Lists in Data Structure

What is a Linked list? A linked list is a data structure that consists of a sequence of elements, where each containing a reference or ("link") to the next element in...

5 minutes read.

Huffman tree in Data Structures

The Huffman trees in the field of data structures are pretty impressive in their work. They are generally treated as the binary tree, which is linked with the least external...

6 minutes read.

Fundamental of Algorithms

An algorithm is a part of any programming solution or coding. If we have to make a solution then first we have to think of a clear idea about the...

13 minutes read.

Shell Sort

Shell Sort: Shell sort is a sorting algorithm. It is an extended version of the insertion sort. In this sorting, we compare the elements that are distant apart rather than the...

5 minutes read.

Operations on Queue in Data Structures

A queue is a linear structure where operations are done in a specific sequence. Queues are abstract data structures that are comparable to Stacks. A queue, unlike a stack, is...

8 minutes read.