C++ Program to Implement Insertion Sort

Problem Description

Write a C++ program to sort the given data using Insertion Sort.

What is Insertion Sort?

Insertion Sort in C++ is a simple sorting algorithm that works by dividing the list into sorted and unsorted portions. It repeatedly picks a value from the unsorted portion and inserts it into its correct position in the sorted portion of the list.

Insertion Sort Algorithm

Here’s the pseudo code for the Insertion Sort algorithm in C++ for a list:

procedure insertionSort(list: array of elements)
    n = length(list)
    for i = 1 to n-1
        key = list[i]
        j = i - 1
        while j >= 0 and list[j] > key
            list[j+1] = list[j]
            j = j - 1
        list[j+1] = key
    end for
end procedure

In the above pseudo code, list represents the array or list to be sorted. The insertionSort procedure iterates through the list starting from the second element (index 1). It selects each element and compares it with the elements before it, shifting elements to the right until it finds the correct position for the selected element. This process is repeated until the entire list is sorted in ascending order.

Problem Solution

1. This algorithm is based on sorting playing cards by picking and inserting them one by one.
2. Here we take data element and place it in sorted list.
3. It should be placed so that list remains sorted.
4. Display the result.
5. Exit.

Insertion Sort Working Procedure

Here’s a simple step-by-step example of how the Insertion Sort algorithm works for the list [15, 8, 3, 11, 6]:

  • Start with an unsorted list: [15, 8, 3, 11, 6].
  • Step 1:Take one element at a time and insert it into its correct position in the sorted part of the list.
  • Step 2: Compare 8 with 15, insert 8 before 15: [8, 15, 3, 11, 6].
  • Step 3: Compare 3 with 15 and 8, insert 3 before them: [3, 8, 15, 11, 6].
  • Step 4: Compare 11 with 15, insert 11 after 8: [3, 8, 11, 15, 6].
  • Step 5: Compare 6 with 15, 11, and 8, insert 6 before them: [3, 6, 8, 11, 15].
  • The list is now sorted in ascending order: [3, 6, 8, 11, 15].
Implementation of Insertion Sort

This program is successfully run on Dev-C++ using TDM-GCC 4.9.2 MinGW compiler on a Windows system.

 * C++ program to implement Insertion Sort using linked lists
#include <iostream>
using namespace std;
// A structure to represent a node.
struct list
    int data;
    list *next;
// Function implementing insertion sort.
list* InsertinList(list *head, int n)
    // Creating newnode and temp node.
    list *newnode = new list;
    list *temp = new list;
    // Using newnode as the node to be inserted in the list.
    newnode->data = n;
    newnode->next = NULL;
    // If head is null then assign new node to head.
    if(head == NULL)
        head = newnode;
        return head;
        temp = head;
        // If newnode->data is lesser than head->data, then insert newnode before head.
        if(newnode->data < head->data)
            newnode->next = head;
            head = newnode;
            return head;
        // Traverse the list till we get value more than newnode->data.
        while(temp->next != NULL)
            if(newnode->data < (temp->next)->data)
        // Insert newnode after temp.
        newnode->next = temp->next;
        temp->next = newnode;
        return head;
int main()
    int n, i, num;
    // Declaring head of the linked list.
    list *head = new list;
    head = NULL;
    cout<<"\nEnter the number of data element to be sorted: ";
    for(i = 0; i < n; i++)
        cout<<"Enter element "<<i+1<<": ";
        // Inserting num in the list.
        head = InsertinList(head, num);
    // Display the sorted data.
    cout<<"\nSorted Data ";
    while(head != NULL)
        head = head->next;
    return 0;
Program Explanation

1. Create a head node of the list structure.
2. Take input of data and simultaneously insert it into a list using InsertinList().
3. Assign the new element as newnode.
4. If the head is null then assign newnode to head.
5. Otherwise, insert the newnode so that list remains sorted.
6. Return head to main.
7. Display the result.
8. Exit.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

Time Complexity: O(n2)
The time complexity of the provided code is O(n2) in the worst case, where “n” is the number of elements in the list.

Space Complexity: O(1)
The space complexity is O(1) since the additional space used is constant and does not depend on the input size.

Runtime Test Cases
<strong>Case 1: (Average Case)</strong>
Enter the number of data element to be sorted: 5
Enter element 1: 998
Enter element 2: 451
Enter element 3: 2
Enter element 4: 35
Enter element 5: 1206
Sorted Data ->2->35->451->998->1206
<strong>Case 2: (Best Case)</strong>
Enter the number of data element to be sorted: 5
Enter element 1: 99845
Enter element 2: 564
Enter element 3: 332
Enter element 4: 86
Enter element 5: 1
Sorted Data ->1->86->332->564->99845
<strong>case 3: (Worst Case)</strong>
Enter the number of data element to be sorted: 5
Enter element 1: 2
Enter element 2: 332
Enter element 3: 456
Enter element 4: 1024
Enter element 5: 16565
Sorted Data ->2->332->456->1024->16565

To practice programs on every topic in C++, please visit “Programming Examples in C++”, “Data Structures in C++” and “Algorithms in C++”.


Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.