Insertion Sort
About
Insertion sort is a sorting algorithm, that compares the entries of an array/list and builts its entries one at a time.It is a good algorithm for sorting a small number of elements.It is often compared to the process of sorting a deck of cards.Let’s see how it works.
The Sorting Problem
We have a sequence of n numbers.
![]()
and we want to get a permutation
![]()
that meets the following property :
![]()
In other words, to sort the sequence of n numbers.
Implementation
#include<iostream>
using namespace std;
void insertionSort(int a[], int n)
{
int i, j;
for(j = 1; j < n; j++)
{
int key = a[j];
i = j - 1;
while((i >= 0) && (a[i] > key))
{
a[i + 1] = a[i];
i = i - 1;
}
a[i + 1] = key;
}
}
int main()
{
int v[] = { 5, 3, 2, 9, 4, 7, 6, 10, 1, 8 };
int n = sizeof(v) / 4;
insertionSort(v, n);
for(int i = 0; i < n; i++)
cout << v[i] << endl;
cin >> v[0];
}
Visual representation and explanation

In the image above we see what happens for each iteration of j.j represents both the “inserted” element as well as the one that we use to compare with the rest of the elements, in order to sort them.The vertical lines are used to delimit and show you the part of the array in which the iteration works.Elements to the left of A[j] that are greater than A[j] move one position to the right, and A[j] moves into the freed position.
Least but not last, we have the final sorted array.
Best, worst, and average cases
The best case performance has an O(n) complexity, or linear complexity.This occurs when the input array is already sorted.
The average case performance and the worst case performance, both have an O(n^2) complexity.
In the worst case performance, the input array is sorted in reverse order.
Related posts:
9 Comments
Trackbacks/Pingbacks
- insertion sort - [...] and Java ... The worst-case data for an insertion sort is an array with all elements sorted in ...Insertion ...
Hi, first I want to say awesome blog. I don’t always agree with your posts but it’s always a interesting read.
Thank you! Stay in tune for more posts
Very nice post. Do you accept guest writers?
Thank you.Unfortunately, for the moment, we don’t accept guest writers, but if you have something to propose, we look forward to hear about it.
I appreciate your website a lot. Will read more. Keep up to excellent writing on it. Gracias
Thanks very much !
Nice, detailed article
I’m glad you like it!
Good share, great article, very usefull for us thanks.