Skip to main content

Insertion Sort Algorithm In C#


In this article i am going to explain about the Insertion sort algorithm.Insertion Sort is based on the idea of consuming one element from input array in each iteration to find its correct position in sorted array.This algorithm is efficient for smaller datasets.

So first I am going to explain insertion sort algorithm then I will be providing a C# code to execute it.

The Insertion Sort Algorithm

Insertion sort compares the current element with largest value in the sorted array. If the current element is smaller then the algorithm finds its correct position in sorted array and moves the element to that position otherwise if the current element is greater then it leaves the element in its place and moves on to next element.

To place the element in its correct position in sorted array, all the elements larger than the current element is shifted one place ahead.Thus the sorted array will grow at each iteration.

Let us understand this with the help of an example.

Let us take input array as : 8 5 7 3 1

The sorted output for this array is : 1 3 5 7 8

IterationsInput ArraySorted ArrayUnSorted Array
Iteration 1 8 5 7 3 1 8 5 7 3 1
Iteration 28 5 7 3 158 7 3 1
Iteration 35 8 7 3 15 78 3 1
Iteration 45 7 8 3 13 5 78 1
Iteration 53 5 7 8 11 3 5 78

Hence we got the sorted array in iteration 5.

Time Complexity

Every element is compared to every other element of sorted array. Hence complexity of Insertion sort is O(n²).

See Also


In this tutorial we learned about the Insertion sort algorithm and its implementation using C#.

You can download the source code from here

Ankit Sharma

C# Corner MVP | Dzone MVB | Author | Speaker | Senior Software Engineer | Passionate Programmer

Leave a Reply

Your e-mail address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.