Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Quick Sort
  • Merge Sort
  • Insertion Sort
  • Selection Sort
  • Heap Sort
  • Sorting Complexities
  • Radix Sort
  • ShellSort
  • Counting Sort
  • Bucket Sort
  • TimSort
  • Bitonic Sort
  • Uses of Sorting Algorithm
Open In App
Next Article:
C Program For Insertion Sort
Next article icon

Insertion Sort Algorithm

Last Updated : 22 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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 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.

  • We start with the second element of the array as the first element is assumed to be sorted.
  • Compare the second element with the first element if the second element is smaller then swap them.
  • Move to the third element, compare it with the first two elements, and put it in its correct position
  • Repeat until the entire array is sorted.


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
5 6 11 12 13  

Illustration

Insertion-sorting

arr = {23, 1, 10, 5, 2}

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]

Complexity Analysis of Insertion Sort

Time Complexity

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

Space Complexity

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

Please refer Complexity Analysis of Insertion Sort for details.

Advantages and Disadvantages of Insertion Sort

Advantages

  • Simple and easy to implement.
  • Stable sorting algorithm.
  • Efficient for small lists and nearly sorted lists.
  • Space-efficient as it is an in-place algorithm.
  • 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

  • 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.

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.

What is the Algorithmic Paradigm of the Insertion Sort algorithm?

The Insertion Sort algorithm follows an incremental approach.

Is Insertion Sort an in-place sorting algorithm?

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

Is Insertion Sort a stable algorithm?

Yes, insertion sort is a stable sorting algorithm.

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.



Next Article
C Program For Insertion Sort
author
kartik
Improve
Article Tags :
  • DSA
  • Sorting
  • Accenture
  • Cisco
  • Dell
  • Grofers
  • Juniper Networks
  • MAQ Software
  • Veritas
Practice Tags :
  • Accenture
  • Cisco
  • Dell
  • Grofers
  • Juniper Networks
  • MAQ Software
  • Veritas
  • Sorting

Similar Reads

  • Insertion Sort Algorithm
    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 like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
    9 min read
  • Insertion Sort in Different languages

    • C Program For Insertion Sort
      Insertion sort is a simple sorting algorithm used to sort a collection of elements in a given order. It is less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort but it is simple to implement and is suitable to sort small data lists. In this article, w
      4 min read

    • C++ Program For Insertion Sort
      Insertion sort is a simple sorting algorithm that works by dividing the array into two parts, sorted and unsorted part. In each iteration, the first element from the unsorted subarray is taken and it is placed at its correct position in the sorted array. In this article, we will learn to write a C++
      3 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 a
      1 min read

    • Java Program for Insertion Sort
      Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. In this article, we will write the program on Insertion Sort in Java. Please refer complete article on Insertion Sort for more details! Algorithm of Insertion SortThe algorithm of Insertion Sort is me
      2 min read

    • Insertion Sort - Python
      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. The insertionSort function takes an array arr as input. It first calculates the length of the array (n). If the length is 0 or
      3 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
    15+ min read
  • Binary Insertion Sort in Different languages

    • C Program for Binary Insertion Sort
      We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected item at each iteration. In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to
      5 min read

    • Python Program for Binary Insertion Sort
      We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected item at each iteration. In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to
      3 min read

    Recursive Insertion Sort in Different languages

    • Java Program for 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 sort Algorithm // 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-
      2 min read

    Insertion Sort on Linked List

    • 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 curr
      3 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
      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 ru
      2 min read

    Problem on Insertion Sort

    • 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 o
      2 min read

    • Given a linked list which is sorted, how will you insert in sorted way
      Given a sorted linked list and a value to insert, write a function to insert the value in a sorted way.Initial Linked List Linked List after insertion of 9 Recommended PracticeInsert in a Sorted ListTry It! Algorithm: Let input linked list is sorted in increasing order. 1) If Linked list is empty th
      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. C
      15 min read

    • How to visualize selection and insertion sort using Tkinter in Python?
      In this article, we are going to create a GUI application that will make us visualize and understand two of the most popular sorting algorithms better, using Tkinter module.  Those two sorting algorithms are selection sort and insertion sort.   Selection sort and Insertion sort are the two most popu
      6 min read

    • Sorting algorithm visualization : Insertion Sort
      An algorithm like Insertion Sort can be understood easily by visualizing. In this article, a program that visualizes the Insertion Sort Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in python using pygame library. Approach: Generate random array and fill the pygame
      3 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences