Insertion Sort Algorithm

Last Updated : 07 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is a stable sorting algorithm, meaning that elements with equal values maintain their relative order in the sorted output.

Insertion sort is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. Then, you pick a card from the unsorted group and put it in the right place in the sorted group.

Insertion Sort Algorithm:

Insertion sort is a simple sorting algorithm that works by building a sorted array one element at a time. It is considered an ” in-place ” sorting algorithm, meaning it doesn’t require any additional memory space beyond the original array.

To achieve insertion sort, follow these steps:

  • We start with second element of the array as first element in the array is assumed to be sorted.
  • Compare second element with the first element and check if the second element is smaller then swap them.
  • Move to the third element and compare it with the second element, then the first element and swap as necessary to put it in the correct position among the first three elements.
  • Continue this process, comparing each element with the ones before it and swapping as needed to place it in the correct position among the sorted elements.
  • Repeat until the entire array is sorted.

Working of Insertion Sort Algorithm:

Consider an array having elements : {23, 1, 10, 5, 2}

Insertion-sorting

Initial:

  • Current element is 23
  • The first element in the array is assumed to be sorted.
  • The sorted part until 0th index is : [23]

First Pass:

  • Compare 1 with 23 (current element with the sorted part).
  • Since 1 is smaller, insert 1 before 23 .
  • The sorted part until 1st index is: [1, 23]

Second Pass:

  • Compare 10 with 1 and 23 (current element with the sorted part).
  • Since 10 is greater than 1 and smaller than 23 , insert 10 between 1 and 23 .
  • The sorted part until 2nd index is: [1, 10, 23]

Third Pass:

  • Compare 5 with 1 , 10 , and 23 (current element with the sorted part).
  • Since 5 is greater than 1 and smaller than 10 , insert 5 between 1 and 10
  • The sorted part until 3rd index is : [1, 5, 10, 23]

Fourth Pass:

  • Compare 2 with 1, 5, 10 , and 23 (current element with the sorted part).
  • Since 2 is greater than 1 and smaller than 5 insert 2 between 1 and 5 .
  • The sorted part until 4th index is: [1, 2, 5, 10, 23]

Final Array:

  • The sorted array is: [1, 2, 5, 10, 23]

To deepen your understanding of sorting algorithms like insertion sort and other essential data structures, consider enrolling in our comprehensive course, Tech Interview 101 – From DSA to System Design . This course covers data structures and algorithms from basic to advanced levels , ensuring you have a solid foundation to excel in technical exams and interviews. Building this knowledge is crucial for your success in the tech industry.

Implementation of Insertion Sort:

C++
// C++ program for implementation of Insertion Sort
#include <iostream>
using namespace std;

/* Function to sort array using insertion sort */
void insertionSort(int arr[], int n)
{
    for (int i = 1; i < n; ++i) {
        int key = arr[i];
        int j = i - 1;

        /* Move elements of arr[0..i-1], that are
           greater than key, to one position ahead
           of their current position */
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}

/* A utility function to print array of size n */
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; ++i)
        cout << arr[i] << " ";
    cout << endl;
}

// Driver method
int main()
{
    int arr[] = { 12, 11, 13, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);

    insertionSort(arr, n);
    printArray(arr, n);

    return 0;
}

/* This code is contributed by Hritik Shah. */
C
// C program for implementation of Insertion Sort
#include <stdio.h>

/* Function to sort array using insertion sort */
void insertionSort(int arr[], int n)
{
    for (int i = 1; i < n; ++i) {
        int key = arr[i];
        int j = i - 1;

        /* Move elements of arr[0..i-1], that are
           greater than key, to one position ahead
           of their current position */
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}

/* A utility function to print array of size n */
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; ++i)
        printf("%d ", arr[i]);
    printf("\n");
}

// Driver method
int main()
{
    int arr[] = { 12, 11, 13, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);

    insertionSort(arr, n);
    printArray(arr, n);

    return 0;
}

/* This code is contributed by Hritik Shah. */
Java
// Java program for implementation of Insertion Sort
public 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;

            /* Move elements of arr[0..i-1], that are
               greater than key, to one position ahead
               of their current position */
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j = j - 1;
            }
            arr[j + 1] = key;
        }
    }

    /* A utility function to print array of size n */
    static void printArray(int arr[])
    {
        int n = arr.length;
        for (int i = 0; i < n; ++i)
            System.out.print(arr[i] + " ");

        System.out.println();
    }

    // Driver method
    public static void main(String args[])
    {
        int arr[] = { 12, 11, 13, 5, 6 };

        InsertionSort ob = new InsertionSort();
        ob.sort(arr);

        printArray(arr);
    }
}

/* This code is contributed by Hritik Shah. */
Python
# Python program for implementation of Insertion Sort

# Function to sort array using insertion sort
def insertionSort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1

        # Move elements of arr[0..i-1], that are
        # greater than key, to one position ahead
        # of their current position
        while j >= 0 and key < arr[j]:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key

# A utility function to print array of size n
def printArray(arr):
    for i in range(len(arr)):
        print(arr[i], end=" ")
    print()

# Driver method
if __name__ == "__main__":
    arr = [12, 11, 13, 5, 6]
    insertionSort(arr)
    printArray(arr)

    # This code is contributed by Hritik Shah.
C#
// C# program for implementation of Insertion Sort
using System;

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;

            /* Move elements of arr[0..i-1], that are
               greater than key, to one position ahead
               of their current position */
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j = j - 1;
            }
            arr[j + 1] = key;
        }
    }

    /* A utility function to print array of size n */
    static void printArray(int[] arr) {
        int n = arr.Length;
        for (int i = 0; i < n; ++i)
            Console.Write(arr[i] + " ");

        Console.WriteLine();
    }

    // Driver method
    public static void Main() {
        int[] arr = { 12, 11, 13, 5, 6 };

        InsertionSort ob = new InsertionSort();
        ob.sort(arr);

        printArray(arr);
    }
}

/* This code is contributed by Hritik Shah. */
JavaScript
// Javascript program for insertion sort 

// Function to sort array using insertion sort
function insertionSort(arr) {
    for (let i = 1; i < arr.length; i++) {
        let key = arr[i];
        let j = i - 1;

        /* Move elements of arr[0..i-1], that are
           greater than key, to one position ahead
           of their current position */
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}

// A utility function to print array of size n
function printArray(arr) {
    console.log(arr.join(" "));
}

// Driver method
let arr = [12, 11, 13, 5, 6];

insertionSort(arr);
printArray(arr);

// This code is contributed by Hritik Shah.
PHP
<?php 
// PHP program for insertion sort

// Function to sort an array using insertion sort
function insertionSort(&$arr, $n)
{
    for ($i = 1; $i < $n; $i++)
    {
        $key = $arr[$i];
        $j = $i - 1;

        // Move elements of arr[0..i-1],
        // that are greater than key, to 
        // one position ahead of their 
        // current position
        while ($j >= 0 && $arr[$j] > $key)
        {
            $arr[$j + 1] = $arr[$j];
            $j = $j - 1;
        }
        
        $arr[$j + 1] = $key;
    }
}

// A utility function to print an array of size n
function printArray(&$arr, $n)
{
    for ($i = 0; $i < $n; $i++)
        echo $arr[$i] . " ";
    echo "\n";
}

// Driver Code
$arr = array(12, 11, 13, 5, 6);
$n = sizeof($arr);
insertionSort($arr, $n);
printArray($arr, $n);

// This code is contributed by Hritik Shah.
?>

Output

Number of passes: 4
5 6 11 12 13

Time Complexity: O(N^2)
Auxiliary Space: O(1)

Complexity Analysis of Insertion Sort :

Time Complexity of Insertion Sort

  • Best case: O(n) , If the list is already sorted, where n is the number of elements in the list.
  • Average case: O(n 2 ) , If the list is randomly ordered
  • Worst case: O(n 2 ) , If the list is in reverse order

Space Complexity of Insertion Sort

  • Auxiliary Space: O(1), Insertion sort requires O(1) additional space, making it a space-efficient sorting algorithm.

Advantages of Insertion Sort:

  • Simple and easy to implement.
  • Stable sorting algorithm.
  • Efficient for small lists and nearly sorted lists.
  • Space-efficient.
  • Adoptive. the number of inversions is directly proportional to number of swaps. For example, no swapping happens for a sorted array and it takes O(n) time only.

Disadvantages of Insertion Sort:

  • Inefficient for large lists.
  • Not as efficient as other sorting algorithms (e.g., merge sort, quick sort) for most cases.

Applications of Insertion Sort:

Insertion sort is commonly used in situations where:

  • The list is small or nearly sorted.
  • Simplicity and stability are important.
  • Used as a subroutine in Bucket Sort
  • Can be useful when array is already almost sorted (very few inversions)
  • Since Insertion sort is suitable for small sized arrays, it is used in Hybrid Sorting algorithms along with other efficient algorithms like Quick Sort and Merge Sort. When the subarray size becomes small, we switch to insertion sort in these recursive algorithms. For example IntroSort and TimSort use insertions sort.

Frequently Asked Questions on Insertion Sort

Q1. What are the Boundary Cases of the Insertion Sort algorithm?

Insertion sort takes the maximum time to sort if elements are sorted in reverse order. And it takes minimum time (Order of n) when elements are already sorted.

Q2. What is the Algorithmic Paradigm of the Insertion Sort algorithm?

The Insertion Sort algorithm follows an incremental approach.

Q3. Is Insertion Sort an in-place sorting algorithm?

Yes, insertion sort is an in-place sorting algorithm.

Q4. Is Insertion Sort a stable algorithm?

Yes, insertion sort is a stable sorting algorithm.

Q5. When is the Insertion Sort algorithm used?

Insertion sort is used when number of elements is small. It can also be useful when the input array is almost sorted, and only a few elements are misplaced in a complete big array.



Similar Reads

Comparison among Bubble Sort, Selection Sort and Insertion Sort
Bubble Sort, Selection Sort, and Insertion Sort are simple sorting algorithms that are commonly used to sort small datasets or as building blocks for more complex sorting algorithms. Here's a comparison of the three algorithms: Bubble Sort:Time complexity: O(n^2) in the worst and average cases, O(n) in the best case (when the input array is already
15 min read
Insertion sort to sort even and odd positioned elements in different orders
We are given an array. We need to sort the even positioned elements in the ascending order and the odd positioned elements in the descending order. We must apply insertion sort to sort them.Examples: Input : a[] = {7, 10, 11, 3, 6, 9, 2, 13, 0} Output : 11 3 7 9 6 10 2 13 0 Even positioned elements after sorting int ascending order : 3 9 10 13 Odd
7 min read
Sorting by combining Insertion Sort and Merge Sort algorithms
Insertion sort: The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.Advantages: Following are the advantages of insertion sort: If the size of the list to be sorted is small, insertion sort runs fasterInsertion sort takes O(N) time when eleme
2 min read
Merge Sort vs. Insertion Sort
Pre-requisite: Merge Sort, Insertion Sort Merge Sort: is an external algorithm based on divide and conquer strategy. In this sorting:   The elements are split into two sub-arrays (n/2) again and again until only one element is left.Merge sort uses additional storage for sorting the auxiliary array.Merge sort uses three arrays where two are used for
14 min read
Count swaps required to sort an array using Insertion Sort
Given an array A[] of size N (1 ≤ N ≤ 105), the task is to calculate the number of swaps required to sort the array using insertion sort algorithm. Examples: Input: A[] = {2, 1, 3, 1, 2} Output: 4 Explanation: Step 1: arr[0] stays in its initial position. Step 2: arr[1] shifts 1 place to the left. Count = 1. Step 3: arr[2] stays in its initial posi
15 min read
Insertion Sort by Swapping Elements
Insertion Sort is suitable for arrays of small size. It also achieves the best-case complexity of O(n) if the arrays are already sorted. We have discussed both Iterative Insertion Sort and Recursive Insertion Sort. In this article, slightly different implementations for both iterative and recursive versions are discussed. Iterative Insertion Sort:
11 min read
Insertion Sort Visualization using JavaScript
Insertion sort is a simple sorting algorithm in which values from the unsorted part are picked and placed at the correct position in the sorted part. In order to know more about it. Please refer Insertion Sort. An algorithm like Insertion Sort can be easily understood by visualizing instead of long codes. In this article, Insertion Sort Visualizer
5 min read
Sorting an Array in Bash using Insertion Sort
Given an array, arr[] of size N, the task is to sort the array in ascending order using Insertion Sort in bash scripting. Examples: Input: arr[] = {9, 7, 2, 5}Output: 2 5 7 9Explanation: The array in sorted order is {2, 5, 7, 9} Input: arr[] = {3, 2, 1}Output: 1 2 3Explanation: The array in sorted order is {1, 2, 3} Approach: Follow the steps below
2 min read
Binary Insertion Sort
Binary insertion sort is a sorting algorithm which is similar to the insertion sort, but instead of using linear search to find the location where an element should be inserted, we use binary search. Thus, we reduce the comparative value of inserting a single element from O (N) to O (log N). It is a flexible algorithm, which means it works faster w
15+ min read
Time complexity of insertion sort when there are O(n) inversions?
What is an inversion? Given an array arr[], a pair arr[i] and arr[j] forms an inversion if arr[i] j. For example, the array {1, 3, 2, 5} has one inversion (3, 2) and array {5, 4, 3} has inversions (5, 4), (5, 3) and (4, 3). We have discussed a merge sort based algorithm to count inversions What is the time complexity of Insertion Sort when there ar
1 min read
An Insertion Sort time complexity question
Question : How much time Insertion sort takes to sort an array of size n in below form? arr[] = 2, 1, 4, 3, 6, 5,....i, i-1, .....n, n-1 Answer : At first look, it seems like Insertion Sort would take O(n2) time, but it actually takes O(n) time How? Let us take a closer look at below code. /* Function to sort an array using insertion sort*/ void in
2 min read
Recursive Insertion Sort
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.Below is an iterative algorithm for insertion sortAlgorithm // Sort an arr[] of size n insertionSort(arr, n) Loop from i = 1 to n-1. a) Pick element arr[i] and insert it into sorted sequence arr[0..i-1] Example: Refer Insertion Sort for more details.H
6 min read
Insertion sort using C++ STL
Implementation of Insertion Sort using STL functions. Pre-requisites : Insertion Sort, std::rotate, std::upper_bound, C++ Iterators. The idea is to use std::upper_bound to find an element making the array unsorted. Then we can rotate the unsorted part so that it ends up sorted. We can traverse the array doing these operations and the result will be
1 min read
Time and Space Complexity of Insertion Sort
What is Insertion Sort?Insertion sort is a simple sorting algorithm that works similarly to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed in the correct position in the sorted part. To sort an array of size N in ascending order itera
2 min read
Top Interview Questions and Answers on Insertion Sort
Insertion sort is a simple sorting algorithm that works similarly to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed in the correct position in the sorted part. In our article “Top Interview Questions and Answers on Insertion Sort”, we
6 min read
Javascript Program For Insertion Sort In A Singly Linked List
We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list. Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list. 2) Traverse the given list, do following for every node. ......a) Insert current node in sorted way in sorted or result list. 3
3 min read
Insertion Sort for Singly Linked List
Given a singly linked list, the task is to sort the list (in ascending order) using the insertion sort algorithm. Examples: Input: 5->4->1->3->2Output: 1->2->3->4->5Input: 4->3->2->1Output: 1->2->3->4 The prerequisite is Insertion Sort on Array. The idea is to gradually build a sorted portion of the list wi
8 min read
Insertion Sort for Doubly Linked List
Given a doubly linked list, the task is to sort the doubly linked list in non-decreasing order using the insertion sort. Examples: Input: head: 5<->3<->4<->1<->2Output: 1<->2<->3<->4<->5Explanation: Doubly Linked List after sorting using insertion sort technique is 1<->2<->3<->4<-
10 min read
Tag sort or Bucket sort or Bin sort in Python
Tag sort, also known as Bucket sort or Bin sort, is a non-comparison based sorting algorithm that distributes elements of an array into a number of "buckets", and then sorts each bucket individually. Tag sort or Bucket sort or Bin sort Algorithm:Determine Range:Find the maximum and minimum values in the input array to determine the range of tags ne
2 min read
Edge Relaxation Property for Dijkstra’s Algorithm and Bellman Ford's Algorithm
In the field of graph theory, various shortest path algorithms especially Dijkstra’s algorithm and Bellmann-Ford’s algorithm repeatedly employ the use of the technique called Edge Relaxation. The idea of relaxation is the same in both algorithms and it is by understanding, the 'Relaxation property' we can fully grasp the working of the two algorith
4 min read
Difference between Greedy Algorithm and Divide and Conquer Algorithm
Greedy algorithm and divide and conquer algorithm are two common algorithmic paradigms used to solve problems. The main difference between them lies in their approach to solving problems. Greedy Algorithm:The greedy algorithm is an algorithmic paradigm that follows the problem-solving heuristic of making the locally optimal choice at each stage wit
3 min read
Algorithm Library | C++ Magicians STL Algorithm
For all those who aspire to excel in competitive programming, only having a knowledge about containers of STL is of less use till one is not aware what all STL has to offer. STL has an ocean of algorithms, for all < algorithm > library functions : Refer here.Some of the most used algorithms on vectors and most useful one's in Competitive Prog
7 min read
What is the stupidest sorting algorithm? (Worst Sorting Algorithm)
Bogo sort stands out as the undisputed champion of stupidity. Unlike other sorting algorithms that follow a structured approach, Bogo sort relies on sheer luck and randomness to achieve its goal. How Bogo Sort Works?Bogo sort operates on the following principle: Randomly shuffle the elements in the list.Check if the list is sorted.If the list is no
2 min read
Difference Between Dijkstra's Algorithm and A* Search Algorithm
Dijkstra's Algorithm and A* Algorithm are two of the most widely used techniques. Both are employed to the find the shortest path between the nodes in a graph but they have distinct differences in their approaches and applications. Understanding these differences is crucial for the selecting the appropriate algorithm for the given problem. What is
3 min read
Z algorithm (Linear time pattern searching Algorithm)
This algorithm efficiently locates all instances of a specific pattern within a text in linear time. If the length of the text is "n" and the length of the pattern is "m," then the total time taken is O(m + n), with a linear auxiliary space. It is worth noting that the time and auxiliary space of this algorithm is the same as the KMP algorithm, but
13 min read
Karatsuba algorithm for fast multiplication using Divide and Conquer algorithm
Given two binary strings that represent value of two integers, find the product of two strings. For example, if the first bit string is "1100" and second bit string is "1010", output should be 120. For simplicity, let the length of two strings be same and be n. A Naive Approach is to follow the process we study in school. One by one take all bits o
15+ min read
C Program for Red Black Tree Insertion
Following article is extension of article discussed here.In AVL tree insertion, we used rotation as a tool to do balancing after insertion caused imbalance. In Red-Black tree, we use two tools to do balancing. Recoloring Rotation We try recoloring first, if recoloring doesn't work, then we go for rotation. Following is detailed algorithm. The algor
6 min read
Insertion in Unrolled Linked List
An unrolled linked list is a linked list of small arrays, all of the same size where each is so small that the insertion or deletion is fast and quick, but large enough to fill the cache line. An iterator pointing into the list consists of both a pointer to a node and an index into that node containing an array. It is also a data structure and is a
11 min read
Kth largest element after every insertion
Given an infinite stream of integers, find the k’th largest element at any point of time. It may be assumed that 1 <= k <= n. Input: stream[] = {10, 20, 11, 70, 50, 40, 100, 5, ...} k = 3 Output: {_, _, 10, 11, 20, 40, 50, 50, ...} Extra space allowed is O(k). The idea is to use min heap. Store first k elements in min heap.For every element f
5 min read
Queries on insertion of an element in a Bitonic Sequence
Given a Bitonic sequence 'S' and 'Q' no. of queries. Each query contain an integer xi, 1 <= i <= Q. The task is to print the length of bitonic sequence after inserting the integer for each query. Also, print the bitonic sequence after all the queries. Examples: Input: S = { 1, 2, 5, 2 }, Q = 4, x = { 5, 1, 3, 2 } Output: 4 5 6 6 Bitonic Seque
9 min read