Insertion Sort by Swapping Elements
Last Updated :
22 Dec, 2022
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:
Let us look at the algorithm for the iterative insertion sort
function insertionSort(V)
i, j, k
for i from 1..length(V)
k = V[i]
j = i-1
while j > 0 and k < V[j]
V[j+1] = V[j]
j -= 1
V[j] = k
return V
Inside the while loop, we shift all values larger than k by one position and then insert k into the first position where k is larger than the array value. The same effect is obtained if we swap consecutive array elements. By repeated swapping, k will travel to its correct position.
Let's take an example to illustrate this
Insert 3 in A = {1, 2, 4, 5, 6}
Put 3 at the end of list.
A = {1, 2, 4, 5, 6, 3}
3 < 6, swap 3 and 6
A = {1, 2, 4, 5, 3, 6}
3 < 5 swap 3 and 5
A = {1, 2, 4, 3, 5, 6}
3 < 4 swap 3 and 4
A = {1, 2, 3, 4, 5, 6}
3 > 2 so stop
By repeatedly swapping 3 travels to its proper position in the list
Therefore the above algorithm can be modified as
function insertionSort(V)
for i in 1...length(V)
j = i
while ( j > 0 and V[j] < V[j-1])
Swap V[j] and V[j-1]
j -= 1
return V
The CPP code for this algorithm is given below
Implementation:
C++
// Iterative CPP program to sort
// an array by swapping elements
#include <iostream>
#include <vector>
using namespace std;
using Vector = vector<int>;
// Utility function to print a Vector
void printVector(const Vector& V)
{
for (auto e : V) {
cout << e << " ";
}
cout << endl;
}
// Function performs insertion sort on
// vector V
void insertionSort(Vector& V)
{
int N = V.size();
int i, j, key;
for (i = 1; i < N; i++) {
j = i;
// Insert V[i] into list 0..i-1
while (j > 0 and V[j] < V[j - 1]) {
// Swap V[j] and V[j-1]
swap(V[j], V[j - 1]);
// Decrement j by 1
j -= 1;
}
}
}
// Driver Code
int main()
{
Vector A = { 9, 8, 7, 5, 2, 1, 2, 3 };
cout << "Array: " << endl;
printVector(A);
cout << "After Sorting :" << endl;
insertionSort(A);
printVector(A);
return 0;
}
Java
// Iterative Java program to sort
// an array by swapping elements
import java.io.*;
import java.util.*;
class GFG
{
// Utility function to print a Vector
static void printVector( Vector<Integer> V)
{
for (int i = 0; i < V.size(); i++) {
System.out.print(V.get(i)+" ");
}
System.out.println();
}
// Function performs insertion sort on
// vector V
static void insertionSort(Vector<Integer> V)
{
int N = V.size();
int i, j, key;
for (i = 1; i < N; i++) {
j = i;
// Insert V[i] into list 0..i-1
while (j > 0 && V.get(j) < V.get(j - 1)) {
// Swap V[j] and V[j-1]
int temp= V.get(j);
V.set(j, V.get(j - 1));
V.set(j - 1, temp);
// Decrement j by 1
j -= 1;
}
}
}
public static void main (String[] args)
{
Vector<Integer> A = new Vector<Integer> ();
A.add(0, 9);
A.add(1, 8);
A.add(2, 7);
A.add(3, 5);
A.add(4, 2);
A.add(5, 1);
A.add(6, 2);
A.add(7, 3);
System.out.print("Array: ");
printVector(A);
System.out.print("After Sorting :");
insertionSort(A);
printVector(A);
}
}
//This code is contributed by Gitanjali.
Python3
# Iterative python program to sort
# an array by swapping elements
import math
# Utility function to print a Vector
def printVector( V):
for i in V:
print(i ,end= " ")
print (" ")
def insertionSort( V):
N = len(V)
for i in range(1,N):
j = i
# Insert V[i] into list 0..i-1
while (j > 0 and V[j] < V[j - 1]) :
# Swap V[j] and V[j-1]
temp = V[j];
V[j] = V[j - 1];
V[j-1] = temp;
# Decrement j
j -= 1
# Driver method
A = [ 9, 8, 7, 5, 2, 1, 2, 3 ]
n = len(A)
print("Array")
printVector(A)
print( "After Sorting :")
insertionSort(A)
printVector(A)
# This code is contributed by Gitanjali.
C#
// Iterative C# program to sort
// an array by swapping elements
using System;
using System.Collections.Generic;
class GFG
{
// Utility function to print a Vector
static void printVector(List<int> V)
{
for (int i = 0; i < V.Count; i++)
{
Console.Write(V[i] + " ");
}
Console.WriteLine();
}
// Function performs insertion sort on
// vector V
static void insertionSort(List<int> V)
{
int N = V.Count;
int i, j;
for (i = 1; i < N; i++)
{
j = i;
// Insert V[i] into list 0..i-1
while (j > 0 && V[j] < V[j - 1])
{
// Swap V[j] and V[j-1]
int temp= V[j];
V[j] = V[j - 1];
V[j - 1] = temp;
// Decrement j by 1
j -= 1;
}
}
}
// Driver Code
public static void Main (String[] args)
{
List<int> A = new List<int> ();
A.Insert(0, 9);
A.Insert(1, 8);
A.Insert(2, 7);
A.Insert(3, 5);
A.Insert(4, 2);
A.Insert(5, 1);
A.Insert(6, 2);
A.Insert(7, 3);
Console.Write("Array: \n");
printVector(A);
Console.Write("After Sorting :\n");
insertionSort(A);
printVector(A);
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Iterative Javascript program to sort
// an array by swapping elements
// Utility function to print a Vector
function printVector(V) {
for (let e of V) {
document.write(e + " ");
}
document.write("<br>");
}
// Function performs insertion sort on
// vector V
function insertionSort(V) {
let N = V.length;
let i, j, key;
for (i = 1; i < N; i++) {
j = i;
// Insert V[i] into list 0..i-1
while (j > 0 && V[j] < V[j - 1]) {
// Swap V[j] and V[j-1]
let temp = V[j];
V[j] = V[j - 1];
V[j - 1] = temp;
// Decrement j by 1
j -= 1;
}
}
}
// Driver Code
let A = [9, 8, 7, 5, 2, 1, 2, 3];
document.write("Array: " + "<br>");
printVector(A);
document.write("After Sorting :" + "<br>");
insertionSort(A);
printVector(A);
// This code is contributed by _saurabh_jaiswal.
</script>
OutputArray:
9 8 7 5 2 1 2 3
After Sorting :
1 2 2 3 5 7 8 9
Time Complexity: O(N*N)
Auxiliary Space: O(1)
Recursive Insertion Sort:
Consider an Array A of size N
- First recursively sort the sublist of A which is of size N-1
- Insert the last element of A into the sorted sublist.
To perform the insertion step use repeated swapping as discussed above.
Algorithm:
function insertionSortRecursive(A, N)
if N >= 1
insertionSortRecursive(A, N-1)
j = N-1
while j > 0 and A[j] < A[j-1]
Swap A[j] and A[j-1]
j = j-1
[end of while]
[end of if]
Following is the implementation of the above approach:
C++
// Recursive CPP program to sort an array
// by swapping elements
#include <iostream>
#include <vector>
using namespace std;
using Vector = vector<int>;
// Utility function to print a Vector
void printVector(const Vector& V)
{
for (auto e : V) {
cout << e << " ";
}
cout << endl;
}
// Function to perform Insertion Sort recursively
void insertionSortRecursive(Vector& V, int N)
{
if (N <= 1)
return;
// General Case
// Sort V till second last element and
// then insert last element into V
insertionSortRecursive(V, N - 1);
// Insertion step
int j = N - 1;
while (j > 0 and V[j] < V[j - 1]) {
// Swap V[j] and V[j-1]
swap(V[j], V[j - 1]);
// Decrement j
j -= 1;
}
}
// Driver Code
int main()
{
// Declare a vector of size 10
Vector A = { 9, 8, 7, 5, 2, 1, 2, 3 };
cout << "Array: " << endl;
printVector(A);
cout << "After Sorting :" << endl;
insertionSortRecursive(A, A.size());
printVector(A);
return 0;
}
Java
// Recursive Java program to sort
// an array by swapping elements
import java.io.*;
import java.util.*;
class GFG
{
// Utility function to print a Vector
static void printVector( Vector<Integer> V)
{
for (int i = 0; i < V.size(); i++) {
System.out.print(V.get(i) + " ");
}
System.out.println();
}
// Function performs insertion sort on
// vector V
static void insertionSortRecursive(Vector<Integer> V,int N)
{
if (N <= 1)
return;
// General Case
// Sort V till second last element and
// then insert last element into V
insertionSortRecursive(V, N - 1);
// Insertion step
int j = N - 1;
// Insert V[i] into list 0..i-1
while (j > 0 && V.get(j) < V.get(j - 1))
{
// Swap V[j] and V[j-1]
int temp= V.get(j);
V.set(j, V.get(j - 1));
V.set(j - 1, temp);
// Decrement j by 1
j -= 1;
}
}
// Driver code
public static void main (String[] args)
{
Vector<Integer> A = new Vector<Integer> ();
A.add(0, 9);
A.add(1, 8);
A.add(2, 7);
A.add(3, 5);
A.add(4, 2);
A.add(5, 1);
A.add(6, 2);
A.add(7, 3);
System.out.print("Array: ");
printVector(A);
System.out.print("After Sorting :");
insertionSortRecursive(A,A.size());
printVector(A);
}
}
// This code is contributed by Gitanjali.
Python3
# Recursive python program
# to sort an array
# by swapping elements
import math
# Utility function to print
# a Vector
def printVector( V):
for i in V:
print(i, end = " ")
print (" ")
# Function to perform Insertion
# Sort recursively
def insertionSortRecursive(V, N):
if (N <= 1):
return 0
# General Case
# Sort V till second
# last element and
# then insert last element
# into V
insertionSortRecursive(V, N - 1)
# Insertion step
j = N - 1
while (j > 0 and V[j] < V[j - 1]) :
# Swap V[j] and V[j-1]
temp = V[j];
V[j] = V[j - 1];
V[j-1] = temp;
# Decrement j
j -= 1
# Driver method
A = [ 9, 8, 7, 5, 2, 1, 2, 3 ]
n=len(A)
print("Array")
printVector(A)
print( "After Sorting :")
insertionSortRecursive(A,n)
printVector(A)
# This code is contributed
# by Gitanjali.
C#
// Recursive C# program to sort
// an array by swapping elements
using System;
using System.Collections.Generic;
class GFG
{
// Utility function to print a Vector
static void printVector(List<int> V)
{
for (int i = 0; i < V.Count; i++)
{
Console.Write(V[i] + " ");
}
Console.WriteLine();
}
// Function performs insertion sort on
// vector V
static void insertionSortRecursive(List<int> V,
int N)
{
if (N <= 1)
return;
// General Case
// Sort V till second last element and
// then insert last element into V
insertionSortRecursive(V, N - 1);
// Insertion step
int j = N - 1;
// Insert V[i] into list 0..i-1
while (j > 0 && V[j] < V[j - 1])
{
// Swap V[j] and V[j-1]
int temp = V[j];
V[j] = V[j - 1];
V[j - 1] = temp;
// Decrement j by 1
j -= 1;
}
}
// Driver code
public static void Main (String[] args)
{
List<int> A = new List<int> ();
A.Insert(0, 9);
A.Insert(1, 8);
A.Insert(2, 7);
A.Insert(3, 5);
A.Insert(4, 2);
A.Insert(5, 1);
A.Insert(6, 2);
A.Insert(7, 3);
Console.Write("Array: ");
printVector(A);
Console.Write("After Sorting :");
insertionSortRecursive(A, A.Count);
printVector(A);
}
}
// This code is contributed by Princi Singh
JavaScript
<script>
// Recursive Javascript program to sort an array
// by swapping elements
// Utility function to print a Vector
function printVector(V) {
for (let e of V) {
document.write(e + " ");
}
document.write("<br>");
}
// Function to perform Insertion Sort recursively
function insertionSortRecursive(V, N) {
if (N <= 1)
return;
// General Case
// Sort V till second last element and
// then insert last element into V
insertionSortRecursive(V, N - 1);
// Insertion step
let j = N - 1;
while (j > 0 && V[j] < V[j - 1]) {
// Swap V[j] and V[j-1]
let temp = V[j];
V[j] = V[j - 1];
V[j - 1] = temp;
// Decrement j
j -= 1;
}
}
// Driver Code
// Declare a vector of size 10
let A = [9, 8, 7, 5, 2, 1, 2, 3];
document.write("Array: <br>");
printVector(A);
document.write("After Sorting :<br>");
insertionSortRecursive(A, A.length);
printVector(A);
// This code is contributed by gfgking.
</script>
OutputArray:
9 8 7 5 2 1 2 3
After Sorting :
1 2 2 3 5 7 8 9
Note: The Time Complexity of the algorithm is still O(N^2) in the worst case. Moreover, these versions are potentially slower since repeated swapping requires more operations. However, these versions are discussed because of their implementation simplicity and ease of understanding.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem