# Insertion Sort Algorithm: What It is, Flow Chart, Time Complexity, and Implementation

Insertion Sort Algorithm: In this tutorial, we will learn about insertion sort, its algorithm, flow chart, and its implementation using C, C++, and Python. By Raunak Goswami Last updated : August 12, 2023

In the last article, we discussed about the bubble sort with algorithm, flowchart and code. In this article, we are going to discuss about another basic sorting technique i.e. **insertion sort**.

## Insertion Sort Algorithm

As the name suggests the sorting is done by using successive **insertions** of the key element selected by the sorting algorithm at its correct place. As the sorting begins the key element chosen is always the second element so that there can be at least one element at the left of the key element to be compared. After comparison the key element is swapped with the element at its left if required and the key element is changed to the element at the immediate right of the previous key element after that the key element is again compared with the elements at it left and the element is swapped with the key element after comparison if required, if the sorting is done in ascending order then the key element should always be greater than the element at its left if not, then the swapping is performed with key element and vice versa for the descending order.

## Insertion Sort Algorithm Pseudo Code

Let us look at the **algorithm of insertion sort** for a better understanding of the logic to be used:

Insertion sort(a[],n)for j->2 to n do key <-a[j] i<-j-1 while i>=0 and a[i]>key do a[i+1]<-a[i] i<-i+1 a[i+1]<-key end

## Insertion Sort Algorithm Flow chart

The insertion algorithm can also be explained in the form of a flowchart as follows:

## Insertion Sort Using C

The below is the implementation of insertion sort using C program:

#include <stdio.h> int main() { int a[6]; int key; int i, j; int temp; printf("Enter any six elements to be sorted using insertion sort\n"); for (i = 0; i < 6; i++) { scanf("%d", &a[i]); } for (j = 1; j < 6; j++) { key = a[j]; i = j - 1; while ((i >= 0) && (a[i] >= key)) { temp = a[i + 1]; a[i + 1] = a[i]; a[i] = temp; i = i - 1; } a[i + 1] = key; } printf("elements after sorting using insertion sort are \n"); for (i = 0; i < 6; i++) { printf("%d \n", a[i]); } return 0; }

The output of the above program will be:

## Insertion Sort Using C++

The below is the implementation of insertion sort using C++ program:

#include <iostream> using namespace std; int main() { int key, i, j, temp; int c, a[100]; cout << "enter the no of elements you want to enter" << endl; cin >> c; cout << "Enter the elements" << endl; for (i = 0; i < c; i++) { cin >> a[i]; } for (j = 1; j < c; j++) { key = a[j]; i = j - 1; while ((i >= 0) && (a[i] >= key)) { temp = a[i + 1]; a[i + 1] = a[i]; a[i] = temp; i = i - 1; } a[i + 1] = key; } cout << "elements after sorting using insertion sort are \n" << endl; for (i = 0; i < 6; i++) { cout << " " << a[i] << endl; } return 0; }

The output of the above program will be:

## Insertion Sort Using Python

The below is the implementation of insertion sort using Python program:

import sys def insertion_sort(arr): # This function will sort the array in non-decreasing order. n = len(arr) # After each iteration first i+1 elements are in sorted order. for i in range(1, n): key = arr[i] j = i-1 # In each iteration shift the 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 return arr # main code if __name__=='__main__': arr = [24, 17, 66, 33, 72, 47, 68, 41, 105, 30] print("Sorted array: ") print(insertion_sort(arr))

The output of the above program will be:

Sorted array: [17, 24, 30, 33, 41, 47, 66, 68, 72, 105]

Related Tutorials

- Introduction to Algorithms
- Introduction to Greedy Strategy in Algorithms
- Stability in sorting
- External Merge Sorting Algorithm
- Radix Sort and its Algorithm
- Bucket Sort Algorithm
- Bubble sort Algorithm, Flow Chart and C++ Code
- Merge Sort | One of the best sorting algorithms used for large inputs
- Binary Search in C, C++
- Randomized Binary Search
- Meta Binary Search | One-sided Binary Search
- Difference between Linear Search and Binary Search
- Binary Search in String
- Variants of Binary Search
- Sieve of Eratosthenes to find prime numbers
- Optimal Merge Pattern (Algorithm and Example)
- Given an array of n numbers, Check whether there is any duplicate or not
- Finding the missing number
- Find the number occurring an odd number of times
- Find the pair whose sum is closest to zero in minimum time complexity
- Find three elements in an array such that their sum is equal to given element K
- Bitonic Search Algorithm
- Check whether a number is Fibonacci or not
- Segregate even and odd numbers in minimum time complexity
- Find trailing zeros in factorial of a number
- Find Nearest Greatest Neighbours of each element in an array
- Interpolation search algorithm
- Floor and ceil of an element in an array using C++
- Two Elements whose sum is closest to zero
- Find a pair with a given difference
- Count number of occurrences (or frequency) in a sorted array
- Find a Fixed Point (Value equal to index) in a given array
- Find the maximum element in an array which is first increasing and then decreasing
- Dynamic Programming (Components, Applications and Elements)
- Algorithm for fractional knapsack problem
- Algorithm and procedure to solve a longest common subsequence problem
- Dynamic Programming (Components, Applications and Elements)
- Find the Nth Fibonacci number | C++
- Longest Common Subsequence using Dynamic programming (DP)
- Longest Increasing Subsequence using Dynamic programming (DP)
- Find the maximum sub-array sum using KADANE'S ALGORITHM
- Non-intersecting chords using Dynamic Programming (DP)
- Edit Distance using Dynamic Programming (DP)
- Finding Ugly Number using Dynamic Programming (DP)
- Egg dropping problem using Dynamic Programming (DP)
- Wild card matching problem using Dynamic programming (DP)
- Compute sum of digits in all numbers from 1 to N for a given N
- Minimum jumps required using Dynamic programming (DP)
- Graph coloring problem's solution using backtracking algorithm
- Breadth First Search (BFS) and Depth First Search (DFS) Algorithms
- Travelling Salesman Problem
- Kruskal's (P) and Prim's (K) Algorithms
- Multistage graph problem with forward approach and backward approach algorithms
- Floyd Warshall algorithm with its Pseudo Code

- Backtracking (Types and Algorithms)
- 4 Queen's problem and solution using backtracking algorithm
- N Queen's problem and solution using backtracking algorithm
- Find the GCD (Greatest Common Divisor) of two numbers using EUCLID'S ALGORITHM
- Compute the value of A raise to the power B using Fast Exponentiation
- Implement First Come First Served (FCFS) CPU Scheduling Algorithm using C program
- Implementations of FCFS scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Non-Preemptive CPU scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Preemptive CPU scheduling algorithm using C++
- Implementation of Priority scheduling (Pre-emptive) algorithm using C++
- Implementation of Priority scheduling (Non Pre-emptive) algorithm using C++
- Implementation of Round Robin CPU Scheduling algorithm using C++
- Analysis of LRU page replacement algorithm and Belady's anomaly
- Branch and Bound
- Find the roots of a complex polynomial equation using Regula Falsi Method in C
- Sieve of Eratosthenes to find prime numbers
- Implementations of FCFS scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Non-Preemptive CPU scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Preemptive CPU scheduling algorithm using C++
- Implementation of Priority scheduling (Pre-emptive) algorithm using C++
- Divide and Conquer Paradigm (What it is, Its Applications, Pros and Cons)
- Implementation of Priority scheduling (Non Pre-emptive) algorithm using C++
- Implementation of Round Robin CPU Scheduling algorithm using C++
- Jump Search Implementation using C++
- Optimal Merge Pattern (Algorithm and Example)
- Introduction to Greedy Strategy in Algorithms
- Strassen's Matrix Multiplication in algorithms
- Huffman Coding (Algorithm, Example and Time complexity)
- Backtracking (Types and Algorithms)
- 4 Queen's problem and solution using backtracking algorithm
- N Queen's problem and solution using backtracking algorithm
- Graph coloring problem's solution using backtracking algorithm
- Tournament Tree and their properties
- Deterministic and Non Deterministic Algorithms
- Lower Bound Theory
- Non Recursive Tree Traversal Algorithm
- Line Drawing Algorithm
- Breadth First Search (BFS) and Depth First Search (DFS) Algorithms
- P and NP problems and solutions | Algorithms
- Travelling Salesman Problem
- 2 – 3 Trees Algorithm
- Kruskal's (P) and Prim's (K) Algorithms
- Algorithm for fractional knapsack problem
- Algorithm and procedure to solve a longest common subsequence problem
- Midpoint Circle Algorithm
- Multistage graph problem with forward approach and backward approach algorithms
- Floyd Warshall algorithm with its Pseudo Code
- Reliability design problem
- Removing consecutive duplicates from a string
- Fast Exponentiation using Bitmasking

Comments and Discussions!