Algorithm

Insertion Sort Algorithm In C#

Introduction

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

Conclusion

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

Full Stack Consultant | GDE for Angular | Microsoft MVP | Author | Speaker | Passionate Programmer

Recent Posts

Announcing A New Blazor Course

Introduction Blazor is a .NET web framework that allows us to create client-side applications using…

3 years ago

How To Solve Sudoku Using Azure Form Recognizer

Introduction In this article, we are going to create a sudoku solver with the help…

4 years ago

Going Serverless With Blazor

Introduction In this article, we will learn how to implement Azure serverless with Blazor web…

4 years ago

Announcing A Free eBook On Angular and Firebase

Introduction Angular is an open-source framework that allows us to create applications for multiple platforms…

5 years ago

Optical Character Reader Using Angular And Azure Computer Vision

Introduction In this article, we will create an optical character recognition (OCR) application using Angular…

5 years ago

Optical Character Reader Using Blazor And Computer Vision

Introduction In this article, we will create an optical character recognition (OCR) application using Blazor…

5 years ago